显示的字符串如下所示:value1,value2,value3,value4,value5等。
一旦我显示它,我想要字符串做什么(删除空格和逗号,我假设我可以使用索引+ 2或其他东西来越过逗号):
值1
值2
等...
lastKnownIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(unformatedList, ",?")) //Currently is ',' can I use ', '?
{
list += unformatedList.Substring(lastKnownIndexPos, m.Index - 1) + "\n\n"; //-1 to grab just the first value.
lastIndex = m.Index + 2; //to skip the comma and the space to get to the first letter of the next word.
//lastIndex++; //used this to count how many times it was found, maxed at 17 (have over 100):(
}
//MessageBox.Show(Convert.ToString(lastIndex)); //used to display total times each was found.
MessageBox.Show(list);
目前消息框没有显示任何文字,但是使用lastIndex我得到的值为17,所以我知道它适用于部分文字:P
答案 0 :(得分:4)
这很容易(我using System.Linq
在这里):
var formatted = string.Join("\n\n", unformatedList.Split(',').Select(x => x.Trim()));
MessageBox.Show(formatted);
swannee指出,另一种方法如下:
var formatted = Regex.Replace(unformatedList, @"\s*,\s*", "\n\n").Trim();
修改强>
无论您如何使用结果字符串,要使上述示例有效,您应使用Environment.NewLine
代替"\n"
。
答案 1 :(得分:2)
一种方法是简单地用换行符替换“,”。
MessageBox.Show( unformatedList.Replace(", ", "\n") );
答案 2 :(得分:2)
或者哎呀,为什么不使用string.Replace?
var formatted = unformattedList.Replace(", ", "\n\n");