I want to split a string in C#. It should split on the basis of a text in the string.Like i have a string "41sugar1100" , i want to split on the base of text in it that is "sugar".How can i do this ?
NOTE: Without passing "sugar" directly as a delimiter.Because text can be change in next iteration.Means wherever it finds text in the string, it should split on the basis of that text.
Use Regex.Split:
string input = "44sugar1100";
string pattern = "[a-zA-Z]+"; // Split on any group of letters
string[] substrings = Regex.Split(input, pattern);
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
char[] array = "41sugar1100".ToCharArray();
StringBuilder sb = new StringBuilder();
// Append letters and special char '#' when original char is a number to split later
foreach (char c in array)
sb.Append(Char.IsNumber(c) ? c : '#');
// Split on special char '#' and remove empty string items
string[] items = sb.ToString().Split('#').Where(s => s != string.Empty).ToArray();
foreach (string item in items)
Console.WriteLine(item);
// Output:
// 41
// 1100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With