[英]How to split for only one string without using arrays
I've a string 01-India
. 我有一个字符串
01-India
。 I want to split on '-' and get only the code 01. How can I do this. 我想拆分' - '并只得到代码01.我怎么能这样做。 I'm a .net newbie.
我是一个.net新手。 Split function returns a array.
Split函数返回一个数组。 Since I need only one string, how can this be done.
由于我只需要一个字符串,如何才能完成。 Is there a ingenious way to do it using split only.
是否有一种巧妙的方法可以使用split进行。 Or do I've to use
substring
only? 或者我只使用
substring
?
您可以搜索第一个出现的 - 然后使用方法子字符串来剪切出来。
var result = input.Substring(0, input.IndexOf('-'))
Other possibility is 其他可能性是
string xy = "01-India";
string xz = xy.Split('-')[0];
Something like this? 像这样的东西?
var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
var str = "01-India";
var hyphenIndex = str.IndexOf("-");
var start = str.substring(0, hyphenIndex);
or you can use regular expression if it is a more complicated string pattern. 或者你可以使用正则表达式,如果它是一个更复杂的字符串模式。
Since you don't want to use arrays, you could do an IndexOf('-') and then a substring. 由于您不想使用数组,因此您可以执行IndexOf(' - '),然后执行子字符串。
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Substring(0, index);
Or, for added fun, you could use String.Remove. 或者,为了增加乐趣,您可以使用String.Remove。
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Remove(index);
string value = "01-India";
string part1 = value.Split('-')[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.