I have this if statement:
if (input == 'day')
Console.Write({0}, dayData);
When the user types 'day' it should be so that the console writes the data in that array. It works fine but is there anyway to get it to work if the user types 'DaY' or 'dAy' etc. I know I could do:
if (input == 'day' || input == 'dAy' || input == 'DaY')
Console.WriteLine({0}, dayData);
But is there anyway to make it shorter and tidier?
Thanks.
The string.Equals method allow you to set up configuration on the comparison and you can set it up to ignore case.
if (string.Equals(input, "day", StringComparison.InvariantCultureIgnoreCase))
if (input.ToLower() == "day") { }
If your code is international, you are writing a library, you want a small speed boost, you are doing this in a loop or with large strings, et cetera, use the following:
if (input.Equals("day", StringComparison.OrdinalIgnoreCase)) { }
Or to use a specific international culture:
if (string.Compare(input, "day", true, new CultureInfo("de-DE")) == 0) { }
The string.Equals method allow you could to check the content of the string and ignore the case, for sample:
if (input.Equals("day", StringComparison.OrdinalIgnoreCase))
{
}
You mention an array so I'll assume you're entering multiple things simultaneously (like 'day', 'dAy', etc)
foreach (var item in input)
{
if (item.ToLower() == "day")
{
Console.WriteLine("{0}", item);
break;
}
}
edit: this would check each item in the array, write to the console, then stop if one was "day".
Another way is
if(str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase))
{
//...
}
Second parameter allow you use one of six predefined comparison modes.
Related
I'm trying to determine if an error message on a generated text file contains the word "multiple", "Database", or both. For each text file I have I'm evaluating which word(s) it contains and for now am just using a messaging box to see how it evaluates. From what I can tell the first if statement is the only one that returns true, even though both text .txt files I have in the folder each only have one of the key words. Code below.
I've searched to see if I have the Exclamation point in the wrong position in the else if statements, but from what I've found it looks right.
string[] files = Directory.GetFiles(#"C:\temp\test", "*.txt");
var multi = "multiple";
var data = "Database";
for (int i = 0; i < files.Length; i++)
{
var sheet = File.ReadAllText(files[i]);
if (multi.Any(sheet.Contains) && data.Any(sheet.Contains))
{
MessageBox.Show("Both");
}
else if (multi.Any(sheet.Contains) && !data.Any(sheet.Contains))
{
MessageBox.Show("Just Multiple");
}else if(!multi.Any(sheet.Contains) && data.Any(sheet.Contains))
{
MessageBox.Show("Just Database");
}
So the first file only has the word "multiple" in it. The first if statement should return false since both conditions aren't met since the first any method returned true while the second shouldn't. But from what I can tell both are returning true.
Let's break down your problem:
multi is a string.
LINQ extension methods (of which .Any() is one) operate on IEnumerable<>.
the enumerable for string is IEnumerable<char>, so .Any() will operate on this.
The string Contains() method will accept a string or a char.
So what's happening? You are checking if any of the characters in multi (i.e. m, u, l, t, i, p, l, e) are found in the string sheet.
What you actually want to write is simply if (sheet.contains(multiple)), etc.
Fixing your current code, it should look like this:
if (sheet.Contains(multi) && sheet.Contains(data))
{
MessageBox.Show("Both");
}
else if (sheet.Contains(multi) && !sheet.Contains(data))
{
MessageBox.Show("Just Multiple");
}
else if(!sheet.Contains(multi) && sheet.Contains(data))
{
MessageBox.Show("Just Database");
}
Though I'd probably avoid doing sheet.Contains over and over (especially on bigger files), and instead do those calculations first:
bool containsMulti = sheet.Contains(multi);
bool containsData = sheet.Contains(data);
if (containsMulti && containsData)
{
MessageBox.Show("Both");
}
else if (containsMulti && !containsData)
{
MessageBox.Show("Just Multiple");
}
else if (!containsMulti && containsData)
{
MessageBox.Show("Just Database");
}
And as #Kristianne Nerona notes, you could simply change the last else if to an else, since if the prior two conditions were both false, only one possibility remains.
I have an IF statement as follows:
if (snumber == "9999-999-9999" && cnumber == "999")
{
// 30 Day Trial Demo Key
return "Good";
}
There's a serial number linked to one or multiple cnumbers. In some cases I have a list of 5-20 cnumbers seperated by commas, but that method will not work for what I'm doing. I believe I need to use the Contains method to let the program know any one of those values will work for that serial number. Any insight or work around?
Thanks
C#
You could split your list of cnumbers by comma and iterate the array checking each cnumber against your value.
if(snumber == "9999-999-9999")
{
var cnumbers = listOfCnumbers.Split(',');
foreach(var cnumber in cnumbers)
{
if(cnumber == "999")
{
return "Good";
}
}
}
Might want to replace the hardcoded strings with variables though
I have this line in my code:
if (address.EndsWith("GIF") || (address.EndsWith("BMP") || address.EndsWith("JPEG") || address.EndsWith("TIFF") || address.EndsWith("RAW") || address.EndsWith("PNG")))
And for example now the website address in the address variable is: www.test.jpg
Then it will never get in the IF and jump out/continue.
I want it to be in all the extensions uppercase and lowercase for example "GIF" and "gif"
How can i do it ?
( sub question If i want to check for file extension doing EndsWith("gif" is enough or i have to add a dot before it like".gif" or like ".jpeg" ? )
Unlike the other answers so far, I'd probably stick with EndsWith but switch to the overload that accepts a StringComparison parameter, e.g.:
address.EndsWith("GIF",StringComparison.OrdinalIgnoreCase)
You should generally avoid using ToLower or ToUpper just to be able to perform a comparison, because most string comparison facilities in the framework offer some form of option that allows you to perform the comparison whilst ignoring case.
For lower case you should just convert to lower and then match the ending.
do it like this
string temp = address.ToLower();
if (temp .EndsWith(".gif") || (temp .EndsWith(".bmp") || temp .EndsWith(".jpeg") || temp .EndsWith(".tiff") || temp .EndsWith(".raw") || temp .EndsWith(".png")))
for your subquestion,
you need to add . in the extension. Because otherwise your address www.testgif will be considered as a valid address.
you simply don't need to
address.ToLower().EndsWith("gif")
if you really need to
bool lowercase = address.ToLower() == address
You could clean up your code too - I believe you should incorporate Damien's answer into this but didn't want to take credit away from where it is due.
var extensions = new string[]{"gif","jpg","something"};
if(extensions.Any(x => address.ToLower().EndsWith(x)))
Get extension using Path.GetExtension method.
Returns the extension of the specified path string.
string ext = Path.GetExtension(address);
Then check all char in extension is uppercase or not.
public static bool IsAllCharLowerCase(string ext)
{
foreach(char c in ext)
{
if (char.IsUpper(c))
{
return false;
}
}
return true;
}
Just change all extensions to upper case before evaluating them, like so
address.ToUpper().EndsWith("GIF") etc.
Checking with the dot e.g. ".GIF" will give you more surety that it actually is an extension and not an extension less file ending in GIF for example.
For some reason i cannot get this if statement to work
if (htmlCode.Contains("Sign out") && !htmlCode.Contains("bye bye"))
{
// do stuff...
}
is there any way to get contains and does not contain to work in same if statement?
First of all check the htmlCode, the text could be mixed with some html tags or something like that, also the issue can be with cases, when trying to find some string in the text you should always remember about cases.
You can use .Contains method or .IndexOf, actually the contains method in the Framework is implemented like this:
public bool Contains(string value)
{
return this.IndexOf(value, StringComparison.Ordinal) >= 0;
}
For comparing large strings without knowing the case I would use:
htmlCode.IndexOf("Sign out", StringComparison.InvariantCultureIgnoreCase);
htmlCode.IndexOf("Bye bye", StringComparison.InvariantCultureIgnoreCase);
If you know that response will be small, you can use .ToLower() or .ToUpper()
Try to compare by converting either upper case or lower case.
if (htmlCode.ToUpper().Contains("SIGN OUT") && !htmlCode.ToUpper().Contains("BYE BYE"))
{
// do stuff...
}
You if clause works correctly
It might be not working because of the string case
So i would suggest you do it this way
if (htmlCode.ToUpper().Contains("Sign out".ToUpper()) && !htmlCode.ToUpper().Contains("bye bye".ToUpper()))
I basically want to check if part of a string begins with a certain sequence - in this case ftp://, or http://. How would I do this?
Thanks
Use String.StartsWith. With just two possible prefixes you can write it as follows:
if (s.StartsWith("http://") || s.StartsWith("ftp://")) { ... }
If you have a lot of different possible prefixes it might be better to use a loop or a LINQ expression instead. For example:
string[] prefixes = { "http://", "ftp://", /* etc... */ };
if (prefixes.Any(prefix => s.StartsWith(prefix)))
{
// ...
}
if(myString.StartsWith("ftp://") || myString.StartsWith("http://")) { }
if you wish it to ignore case then use StringComparison.OrdinalIgnoreCase.
if(myString.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) || myString.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { }
if( myString.StartsWith("ftp://")){
...
}
Similar if you want to check for http://, but change the parameter to StartsWith.
String.StartsWith Method
Personally I'd suggest use Regex, but the most basic form is
string myText = #"http://blabla.com";
if (myText.IndexOf("http://") == 0 || myText.IndexOf("ftp://") == 0))
{
//dosome
}
You should use the String.StartsWith method.