Skip to main content

string.split in c#


Whenever we have a situation where we have to split a string on the basis of a character, we can use this method.
First of all we have to check if that char(needle) exists in the string. We are doing it with indexOf method that tells about the index of the char(needle) in string.
Then we have to just apply split method , that break the string in an array or strings from the index of the needle-char
Let say we have a simple string "I am the_winner"
String Result = "I am the_winner";

// now check if if there is  "_" and split to get user Id 

if (Result.IndexOf("_") != -1)
{
 string[] arr = new string[2];
 arr = Result.Split('_');
 
 console.writeline(arr[0].ToString() + " only " + arr[0].ToString()); 
}
The code broke the string from index of the underscore(_) and created array of strings.
Output will be : I am the only winner

Comments

Popular posts from this blog