[英]How to split a string with non-numbers as delimiter?
I want to split
a string in C#
. 我想在C#
split
一个字符串。 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 ? 它应该基于字符串中的文本进行split
。就像我有一个字符串"41sugar1100"
,我想基于其中的text
即"sugar"
进行split
。我该怎么做?
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. 注意:不能直接将"sugar"
作为delimiter
。因为文本可以在下一次迭代中更改。表示在字符串中找到文本的任何位置,都应在该文本的基础上进行拆分。
Use Regex.Split : 使用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
****Use char[] array for split a string from string**** ****使用char []数组从字符串中拆分字符串****
string s = "44sugar1100";
char[] c = new char[] { 's', 'u', 'g', 'a', 'r' };
string[] s1 = s.Split(c,StringSplitOptions.RemoveEmptyEntries);
string s2 = s1.ToString();
Regex regex = new Regex(@"(?<firstNumber>\d+)(?<word>[^\d]+)+(?<secondNumber>\d+)", RegexOptions.CultureInvariant);
string s = "41sugar1100";
Match match = regex.Match(s);
if (match.Success)
{
string firstNumber = match.Groups["firstNumber"].Value;
string word = match.Groups["word"].Value;
string secondNumber = match.Groups["secondNumber"].Value;
}
I would take the string and put it into a char array then int.tryparse each char in the array for example... 我将字符串放入一个char数组中,然后将其int.tryparse例如数组中的每个char ...
string myString = "44sugar1100";
int num=0; //for storage
string newString="";//for rebuilding
foreach(char ch in myString)
{
if(int.TryParse(ch, out num)
{
newString+=num.toString();
}
}
string text = "41sugar1100";
string[] array = text.Split('sugar');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.