Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with non-numbers as delimiter?

Tags:

c#

split

asp.net

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.

like image 732
user3772251 Avatar asked Jan 30 '26 12:01

user3772251


2 Answers

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);
}
like image 101
Thomas Ayoub Avatar answered Feb 01 '26 00:02

Thomas Ayoub


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  
like image 31
david_rprada Avatar answered Feb 01 '26 02:02

david_rprada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!