Is there a function I can apply to a string that will return true of false if a string contains a character.
I have strings with one or more character options such as:
var abc = "s";
var def = "aB";
var ghi = "Sj";
What I would like to do for example is have a function that would return true or false if the above contained a lower or upper case "s".
if (def.Somefunction("s") == true) { }
Also in C# do I need to check if something is true like this or could I just remove the "== true" ?
The following should work:
You can use the
IndexOf
method, which has a suitable overload for string comparison types:Also, you would not need the
== true
, since an if statement only expects an expression that evaluates to abool
.Use the function String.Contains();
an example call,
here is more from MSDN.
You can use the extension method
.Contains()
from the namespace System.Linq:And no, to check if a boolean expression is true, you don't need
== true
Since the
Contains
method is an extension method, my solution appeared to be confusing to some. Here are two versions that don't require you to addusing System.Linq;
:Update
If you want to, you can write your own extensions method for easier reuse:
Then you can call them like this:
In most cases when dealing with user data, you actually want to use
CurrentCultureIgnoreCase
(or theContainsAnyCase
extension method), because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.For example: In Turkish, the uppercase letter
I
in lowercase isı
(without a dot), and noti
(with a dot).here is an example what most of have done