C# - if statements against parts of a string - c#

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.

Related

Building if condition from array

I have following if condition:
if (!string.IsNullOrEmpty(str) &&
(!str.ToLower().Contains("getmedia") && !str.ToLower().Contains("cmsscripts") &&
!str.ToLower().Contains("cmspages") && !str.ToLower().Contains("asmx") &&
!str.ToLower().Contains("cmsadmincontrols"))
)
I am trying to create an array of keywords instead of putting multiple AND conditions, could you please help?
string[] excludeUrlKeyword = ConfigurationManager.AppSettings["ExcludeUrlKeyword"].Split(',');
for (int i = 0; i < excludeUrlKeyword.Length; i++)
{
var sExcludeUrlKeyword = excludeUrlKeyword[i];
}
How to build the same if condition from the array?
You can use LINQ's All or Any method to evaluate a condition on array elements:
// Check for null/empty string, then ...
var lower = str.ToLower();
if (excludeUrlKeyword.All(kw => !lower.Contains(kw))) {
...
}
Note that this is not the fastest approach: you would be better off with a regex. As an added bonus, regex would prevent "aliasing", when you discard a string with a keyword appearing as part of a longer word.
If you would like to try regex approach, change ExcludeUrlKeyword in the config file from comma-separated getmedia,cmsscripts,cmspages,asmx to pipe-separated getmedia|cmsscripts|cmspages|asmx, so that you could feed it directly to regex:
var excludeUrlRegex = ConfigurationManager.AppSettings["ExcludeUrlKeyword"];
if (!Regex.IsMatch(str.ToLower(), excludeUrlRegex)) {
...
}
Linq Any should do this
if (!string.IsNullOrEmpty(str) && !excludeUrlKeyword.Any(x => str.ToLower().Contains(x)))

C# ignoring letter case for if statement

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.

How can i check if the file extension is uppercase or lowercase?

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.

C# if string contains more than 1 value

Good Morning,
In an if statement if we want to check if a string contains a value, we have :
if (string.Contains("Value1"))
{
}
How can we make the string compare with more values in an if statement without keep writing the whole statement? For example to avoid the below statement
if ((string.Contains("Value1") && (string.Contains("Value2")) && (string.Contains("Value3")))
{
}
Thank you
So, basically, you want to check if all of your values are contained in the string . Fortunately (with the help of LINQ), this can by translated almost literally into C#:
var values = new String[] {"Value1", "Value2", "Value3"};
if (values.All(v => myString.Contains(v))) {
...
}
Similarly, if you want to check if any value is contained in the string, you'd substitute All by Any.
Well, you could use LINQ:
string[] requiredContents = { "Foo", "Bar", "Baz" };
if (requiredContents.All(x => text.Contains(x))
{
...
}
Note that just like the short-circuiting && operator, All will stop as soon as it finds a value which doesn't satisfy the condition. (If you want to use Any in a similar way elsewhere, that will stop as soon as it finds a value which does satisfy the condition.)
I wouldn't bother for only a reasonably small number though. Without the extraneous brackets, it's really not that bad:
if (text.Contains("foo") && text.Contains("bar") && text.Contains("Baz"))
{
}
I would only start using the more general form if either there were genuinely quite a few values (I'd probably draw the line at about 5) or if the set of values was being passed in as a parameter, or varied in some other way.
As you need "your" string to contains all values:
var values = new String[] {"Value1", "Value2", "Value3"};
var s = yourString;
if (values.Count(v => s.Contains(v)) == values.Length) {
...
}
Is this the best solution? Probably not. Is it readable and extendable? Yes.
var matches = {"string1", "string2", "string3","string-n"};
var i = 0;
foreach(string s in matches)
{
if(mystring.Contains(s))
{
i++;
}
}
if(i == matches.Length)
{
//string contains all matches.
}
if(stringArray.Any(s => stringToCheck.Contains(s)))
If you want to ensure that it contains all the substrings, change Any to All:
if(stringArray.All(s => stringToCheck.Contains(s)))

does contain and does not contain in same if

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()))

Categories

Resources