如何分割字符串?
假设我有一个字符串"dog, cat, mouse,bird"
我的实际目标是将每个动物插入到listBox中,使它们成为列表框中的项目。
但是,如果我知道如何拆分字符串,我认为我会想到如何插入这些项目。还有其他更好的方法吗?
我正在使用asp c#。
如何分割字符串?
假设我有一个字符串"dog, cat, mouse,bird"
我的实际目标是将每个动物插入到listBox中,使它们成为列表框中的项目。
但是,如果我知道如何拆分字符串,我认为我会想到如何插入这些项目。还有其他更好的方法吗?
我正在使用asp c#。
string[] tokens = text.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
yourListBox.Add(new ListItem(token[i], token[i]));
}
你尝试过使用String.Split吗?如果你想要把"a, b, c"转换为{"a", "b", "c"},那么你可能需要进行一些后处理来去除空格;但是如果你想要将"a b, c"转换为{"a b", "c"},则不需要进行任何处理。
例如:
private readonly char[] Delimiters = new char[]{','};
private static string[] SplitAndTrim(string input)
{
string[] tokens = input.Split(Delimiters,
StringSplitOptions.RemoveEmptyEntries);
// Remove leading and trailing whitespace
for (int i=0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
}
return tokens;
}
不需要使用 Linq 版本;
from s in str.Split(',')
where !String.IsNullOrEmpty(s.Trim())
select s.Trim();
targetListBox.Items.AddRange(inputString.Split(','));
或者使用以下方法来确保字符串被截断:
targetListBox.Items.AddRange((from each in inputString.Split(',')
select each.Trim()).ToArray<string>());
糟糕!正如评论指出的那样,我错过了它是ASP.NET,所以不能从字符串数组初始化 - 需要像这样做:
var items = (from each in inputString.Split(',')
select each.Trim()).ToArray<string>();
foreach (var currentItem in items)
{
targetListBox.Items.Add(new ListItem(currentItem));
}
通过 strVar.Split,它会给你一个字符串数组
"dog, cat, mouse,bird".Split(new[] { ',' });