[英]How to add “String[] or List<String>” as ONE cell entry in a DataTable in C#?
[英]Add all chars of a string to a list but merge numbers to one entry C#
您已經給定了一個字符串“(32 + 5)* 20”,並且需要創建一個包含所有字符的列表,但是需要將數字合並到一個條目中,例如“ 32”和“ 20”。 怎么做?
我已經嘗試過
string formel = "(32+5)*20";
char[] zeichen = formel.ToCharArray();
var liste = new List<string>();
for(int i = 0; i < zeichen.Length ; i++)
{
if(Char.IsNumber(zeichen[i]) && formel.Substring(i, i + 1).Any(char.IsNumber))
{
liste.Add(zeichen[i].ToString() + zeichen[i+1].ToString());
}
else
{
liste.Add(zeichen[i].ToString());
}
}
您可以使用正則表達式返回數字組:
var formel = "(32+5)*20";
var pattern = "([0-9]+)";
var match = Regex.Match(formel, pattern);
然后使用
match.Groups
發布的列表仍將包含與字符串相同數量的元素,因為您是在每次循環迭代中將其添加到列表中的。 要將“合並”到一個條目中,您無需添加某些迭代,而只需將該數字添加到先前的數字即可。
如果您檢查上一項是否為數字,而不是下一項,則此操作會更容易。
for (int i = 0; i < zeichen.Length; i++)
{
if (i > 0 && Char.IsNumber(zeichen[i]) && Char.IsNumber(zeichen[i - 1])) // if got a number, and had a number before
{
// Then dont Add to the list, instead add to the number/string
liste[list.Count - 1] += zeichen[i];
//liste.Add(zeichen[i].ToString() + zeichen[i + 1].ToString());
}
else
liste.Add(zeichen[i].ToString());
}
// "(", "32", "+", "5", ")", "*", "20"
您可以使用Regex和LINQ來做到這一點
var dateText = "(32 + 5) * 20";
string splitPattern = @"[^\d]";
var result = Regex.Split(dateText, splitPattern).Where(x=>x!="");
希望對您有幫助@Janic
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.