C# 如何将字符串拆分为多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/242718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i split a String into multiple values?
提问by Adyt
How do you split a string?
你如何拆分字符串?
Lets say i have a string "dog, cat, mouse,bird"
假设我有一个字符串“狗,猫,老鼠,鸟”
My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.
我的实际目标是将这些动物中的每一个都插入到一个列表框中,这样它们就会成为列表框中的项目。
but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?
但我想如果我知道如何拆分字符串,我就知道如何插入这些项目。或者有没有人知道更好的方法来做到这一点?
im using asp c#
我使用 asp c#
采纳答案by dove
string[] tokens = text.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
yourListBox.Add(new ListItem(token[i], token[i]));
}
回答by Ray Lu
It gives you a string array by strVar.Split
它通过 strVar.Split 为您提供一个字符串数组
"dog, cat, mouse,bird".Split(new[] { ',' });
回答by Jon Skeet
Have you tried String.Split? You may need some post-processing to remove whitespace if you want "a, b, c" to end up as {"a", "b", "c"} but "a b, c" to end up as {"a b", "c"}.
你试过String.Split吗?如果您希望 "a, b, c" 以 {"a", "b", "c"} 结尾但 "ab, c" 以 {"ab “, “C”}。
For instance:
例如:
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;
}
回答by Gordon Mackie JoanMiro
Or simply:
或者干脆:
targetListBox.Items.AddRange(inputString.Split(','));
Or this to ensure the strings are trimmed:
或者这样可以确保修剪字符串:
targetListBox.Items.AddRange((from each in inputString.Split(',')
select each.Trim()).ToArray<string>());
Oops! As comments point out, missed that it was ASP.NET, so can't initialise from string array - need to do it like this:
哎呀!正如评论指出的那样,错过了它是 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));
}
回答by Ali Ers?z
Needless Linq version;
不需要的 Linq 版本;
from s in str.Split(',')
where !String.IsNullOrEmpty(s.Trim())
select s.Trim();