C# 从字符串中提取子字符串直到找到一个逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1480806/
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
Extract substring from a string until finds a comma
提问by alina
I'm building a page and would like to know how to extract substring from a string until finds a comma in ASP.Net C#. Can someone help please?
我正在构建一个页面,想知道如何从字符串中提取子字符串,直到在 ASP.Net C# 中找到逗号。有人可以帮忙吗?
回答by Ian Devlin
myString = myString.Substring(0,myString.IndexOf(','));
回答by dove
string NoComma = "";
string example = "text before first comma, more stuff and another comma, there";
string result = example.IndexOf(',') == 0 ? NoComma : example.Split(',')[0];
回答by thecoop
substring = str.Split(',')[0];
If str doesn't contain any commas, substring will be the same as str.
如果 str 不包含任何逗号,则 substring 将与 str 相同。
EDIT: as with most things, performance of this will vary for edge cases. If there are lots and lots of commas, this will create lots of String instances on the heap that won't be used. If it is a 5000 character string with a comma near the start, the IndexOf+Substring method will perform much better. However, for reasonably small strings this method will work fine.
编辑:与大多数事情一样,这种情况的性能会因边缘情况而异。如果有很多逗号,这将在堆上创建很多不会使用的 String 实例。如果是开头附近有逗号的 5000 个字符的字符串,IndexOf+Substring 方法的性能会好很多。但是,对于相当小的字符串,此方法可以正常工作。
回答by Vinko Vrsalovic
You can use IndexOf() to find out where is the comma, and then extract the substring. If you are sure it will always have the comma you can skip the check.
您可以使用 IndexOf() 找出逗号在哪里,然后提取子字符串。如果您确定它总是有逗号,您可以跳过检查。
string a = "asdkjafjksdlfm,dsklfmdkslfmdkslmfksd";
int comma = a.IndexOf(',');
string b = a;
if (comma != -1)
{
b = a.Substring(0, comma);
}
Console.WriteLine(b);
回答by Ian Devlin
Alina, based on what you wrote above, then Split will work for you.
Alina,根据您上面写的内容,Split 将为您工作。
string[] a = comment.Split(',');
Given your example string, then a[0] = "aaa", a[1] = "bbbbb", a[2] = "cccc", and a[3] = "dddd"
给定您的示例字符串,然后 a[0] = "aaa"、a[1] = "bbbbb"、a[2] = "cccc" 和 a[3] = "dddd"
回答by Konstantin Spirin
var firstPart = str.Split(new [] { ',' }, 2)[0]
Second parameter tells maximum number of parts. Specifying 2 ensures performance is fine even if there are lots and lots of commas.
第二个参数告诉最大零件数。指定 2 可确保性能良好,即使有很多逗号也是如此。