I get this error
string v = "aeiou";
foreach(int i in lokacija.Naziv) {
if(v.indexOf(lokacija.Naziv[i], StringComparison.CurrentCultureIgnoreCase) = -1)
s+=lokacija.Naziv[i];
}
The error says "cannot convert from System.StringComparison to int". But I know there is an overload of the method indexOf(string) which accepts arguments of the type StringComparison. So how can I resolve this?
First of all, you should be using == for comparison.
Second, all IndexOf overloads whose first parameter is a char, their second parameter is an int. That's why you get that error. In order to use the overload that receives a StringComparison, make that first parameter a string, like this:
if (v.indexOf(lokacija.Naziv[i].ToString(), StringComparison.CurrentCultureIgnoreCase) == -1)
BTW, are you trying to remove vowels from a string? I recommend you try this.
you loop seems strange... did you mean this?
foreach(string ssub in lokacija.Naziv) {
if(v.indexOf(ssub, StringComparison.CurrentCultureIgnoreCase) = -1)
s+=ssub;
#Johnathan-Lonowski hit the nail on the head- you are getting this version of String.IndexOf, not this one, because you are looking for a character in a string, not an occurrence of one string in another.
Related
I have a string which is getting from a userInput. What I want to do now is removing a unique character from this string but only remove it once. The main problem is that this unique character doesn't have a unique index. For example:
User has input a string like : "0123456", and now I want to remove the first '1',so the string will be output like "023456". How ever, if a user input a string like "01123456", how can I remove the first '1' and make it looks like "0123456"? I am looking for a method that can be used for both of situation. I was using string.TrimStart(), but doesn't get what I want. How can I do this?
You could use Remove and IndexOf.
var str = "01123456";
var i = str.IndexOf('1'); // IndexOf returns -1 when there is no element found, so we need to handle that when calling remove.
var res = (i >= 0) ? str.Remove(i, 1) : str;
Console.WriteLine(res); // 0123456
I think you what you need is string.Remove method. See MSDN documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.7.2#System_String_Remove_System_Int32_System_Int32_
If you don't know where is your character, at first call string.IndexOf to find it. If this call returns nonnegaive number, call Remove to remove it. Just note that string is immutable so it will always create a new object.
yourstring = yourstring.IndexOf('1') != -1 ? yourstring.Remove(yourstring.IndexOf('1'), 1) : yourstring;
Another way would be to use a combination of Contains, Remove, and IndexOf:
if (userInput.Contains('1')) userInput = userInput.Remove(userInput.IndexOf('1'), 1);
Or if you want to be Linq-y...
userInput = string.Concat(userInput.TakeWhile(chr => chr != '1')
.Concat(userInput.SkipWhile(chr => chr != '1').Skip(1)));
I'm trying to extract argument and file name from path like below:
C:\Users\user\Desktop\foo.exe foo://action/bar
I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe
Is there any way to get argument and file name?
You can get the command line argument from the string [] args passed to the Main method.
Or you can use the static method Environment.GetCommandLineArgs https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Use LastIndexOf to reverse-search the string for the backslash, then Substring to grab everything beyond that:
int i = path.LastIndexOf(#"\");
return (i > -1 && i < path.Length) ? path.Substring(i + 1) : string.Empty;
If you need to separate the filename and argument, use IndexOf to look for the space or Split the result on the space character.
I have many lines of code like this.. this is just a 1 thing i am trying right now.
if (RI2.Text.Contains("SOS") || RI2.Text.Contains("WAR"))
{
Response.Redirect("http://mydomain.com/rabat");
}
if (RI2.Text.Contains("sos") || RI2.Text.Contains("war"))
{
Response.Redirect("http://mydomain.com/rabat");
}
How do i minify this code. i mean, its very ugly and there many lines of code similar to this.
is there any better way of doing this which i dont know.
please help. appreciate your time and help.
Try this regular expression.
Ignores case in comparison (SOS and sos matched)
Does not mutate the strings as you don't call ToLower()
Only 2 lines of code
You can optionally precompile the expression if the expression (SOS|WAR) is a constant for more performance.
if (Regex.IsMatch(RI2.Text, "SOS|WAR", RegexOptions.IgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Not sure I fully understand your requirements, but here you go:
if(RI2.Text.ToLower().Contains("sos") || RI2.Text.ToLower().Contains("war")) {
Response.Redirect("http://mydomain.com/rabat");
}
you can do one call, like
//this will accept "SOS" and "sos"
if(RI2.Text.ToLower().Contains("sos") ||
RI2.Text.ToLower().Contains("war"))
{
....
}
You could convert the string to lowercase removing one if statement and then use a linq any statement.
var search=new[] {"sos","war"};
if (search.Any(x=>RI2.Text.ToLower().Contains(x))) {
Response.Redirect("http://mydomain.com/rabat");
}
Or even make collection of matches to target urls.
var search = new Dictionary<string,string>{
{"sos","http://mydomain.com/rabat"},
{"war","http://mydomain.com/rabat"},
};
The use linq
var url=search.Keys.Where(x=>RI2.Text.ToLower().Contains(x)).Select(x=>search[x]).FirstOrDefault();
if (url!=null) {
Response.Redirect(url);
}
You could create a extention to string as follows
public static bool Contains(this string value, string[] values)
{
foreach (string comparar in values)
{
if (value.ToUpper().Contains(comparar.ToUpper())) return true;
}
return false;
}
Instead of converting the string to lower or upper case use string.IndexOf with ignore case
if (RI2.Text.IndexOf("sos",StringComparison.InvariantCultureIgnoreCase) >= 0 ||
RI2.Text.IndexOf("war",StringComparison.InvariantCultureIgnoreCase) >= 0 )
{
Response.Redirect("http://mydomain.com/rabat");
}
if(string.Equals("war", RI2.Text, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals("sos", RI2.Text, StringComparison.InvariantCultureIgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Create a list of string pairs, with one being the search string in upper case and the other being the redirect location.
Iterate through the list checking each search string against the upper-case text. If you find a match redirect to the location specified in the pair.
Use Regex:
var pattern = "(sos|war)";
if(Regex.IsMatch(RI2.Text.ToLower(), pattern))
Response.Redirect("http://mydomain.com/rabat");
Given that both the Url for Response.Redirect are same
string lowerRI2 = RI2.Text.ToLower();
if (lowerRI2.Contains("sos") || lowerRI2.Contains("war"))
Response.Redirect("http://mydomain.com/rabat");
I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');
I found an error in my code, where the subtring is not work, it says "startIndex cannot be larger than the length of string"
static int MyIntegerParse(string possibleInt)
{
int i;
return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;
}
I used the procedure here:
var parsed = File.ReadLines(filename)
.Select(line => line.Split(' ')
.Select(MyIntegerParse)
.ToArray())
.ToArray();
But I don't understand why it's error because I already used the substring before and it's work, can I ask for a help here? thnaks.
sample string:
10192 20351 30473 40499 50449 60234
10192 20207 30206 40203 50205 60226
10192 20252 30312 40376 50334 60252
Substring will fail when possibleInt contains fewer than two characters, so you should add that test to your code as well. I suspect that you Split call produces an empty string during some circumstances. This empty string is passed into your int-parser which then fails on the Substring call. So, you should probably do two things:
Get rid of empty strings in the splitting
Handle short or empty strings deliberately in your parsing code
Getting rid of empty strings is quite easy:
var parsed = File.ReadLines(filename)
.Select(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(MyIntegerParse)
.ToArray())
.ToArray();
Adding deliberate handling of empty strings can be done like so:
static int MyIntegerParse(string possibleInt)
{
if (string.IsNullOrEmpty(possibleInt) || possibleInt.Length < 2)
{
return 0;
}
int i;
return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;
}
...or if you are a fan of compact and hard-to-read constructs:
static int MyIntegerParse(string possibleInt)
{
int i;
return (!string.IsNullOrEmpty(possibleInt)
&& possibleInt.Length >= 2
&& int.TryParse(possibleInt.Substring(2), out i)) ? i : 0;
}
No, I have chosen to return 0 when I get strings that are too short. In your case it might make more sense to return some other value, throw an exception or use a Debug.Assert statement.
The possibleInt string needs to be at least two characters long. When it isn't then you'll see the error that you've described.
Add this before your return statement and see if that helps you figure out what's going on:
Debug.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);
When running in Debug mode this will throw an exception if the two cases above are not met.
You could also use a Code Contract like this:
Contract.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);
You are getting this exception because you are trying to get the substring of a string starting at an index that is greater than the length of the string.
someString.Substring(x) will give you the substring of someString starting at position x in the string, and it is zero based. You are getting this exception because in this case 2 is outside the range of the particular strings length.
Stick a try catch around it, or a breakpoint and you will see the string that is causing this exception has a length less than 3.
The line you are attempting to parse is not that long. From the C# Specification on Substring:
The zero-based starting character position of a substring in this instance.
The string you are passing in either has 0 or 1 characters in it. You need to modify your code to handle such a situation.
EDIT: Additionally, you should be removing empty elements from your file using an overload of split:
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntires)