Note: The reason to use the invariant versions of these methods is to prevent producing unexpected culture-specific letters. This is explained here in detail(opens new window).
Example:
string s ="My String";
s = s.ToLowerInvariant();// "my string"
s = s.ToUpperInvariant();// "MY STRING"
Using the
System.String.Contains(opens new window) you can find out if a particular string exists within a string. The method returns a boolean, true if the string exists else false.
string s ="Hello World";bool stringExists = s.Contains("ello");//stringExists =true as the string contains the substring
Using the System.String.IndexOf(opens new window) method, you can locate the starting position of a substring within an existing string.
Note the returned position is zero-based, a value of -1 is returned if the substring is not found.
string s ="Hello World";int location = s.IndexOf("ello");// location = 1
string s =" String with spaces at both ends ";
s = s.Trim();// s = "String with spaces at both ends"
In addition:
To remove white-space only from the **beginning** of a string use: [`System.String.TrimStart`](https://msdn.microsoft.com/en-us/library/system.string.trimstart(v=vs.110).aspx)
To remove white-space only from the **end** of a string use: [`System.String.TrimEnd`](https://msdn.microsoft.com/en-us/library/system.string.trimend(v=vs.110).aspx)
string s ="A portion of word that is retained";
s=str.Substring(26);//s="retained"
s1 = s.Substring(0,5);//s="A por"
Splitting a string using a delimiter
Use the System.String.Split(opens new window) method to return a string array that contains substrings of the original string, split based on a specified delimiter:
string sentence ="One Two Three Four";string[] stringArray = sentence.Split(' ');foreach(string word in stringArray){
Console.WriteLine(word);}
Output:
One
Two
Three
Four
Concatenate an array of strings into a single string
The System.String.Join(opens new window) method allows to concatenate all elements in a string array, using a specified separator between each element:
string[] words ={"One","Two","Three","Four"};string singleString = String.Join(",", words);// singleString = "One,Two,Three,Four"