I've a string 01-India. I want to split on '-' and get only the code 01. How can I do this. I'm a .net newbie. Split function returns a array. Since I need only one string, how can this be done. Is there a ingenious way to do it using split only. Or do I've to use substring only?
views:
88answers:
7
+4
A:
You can search for the first occurence of - and then use the method substring to cut the piece out.
var result = input.Substring(0, input.IndexOf('-'))
schoetbi
2010-08-17 19:23:03
+1
A:
Something like this?
var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));
epitka
2010-08-17 19:23:10
+2
A:
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
James Curran
2010-08-17 19:23:23
Not sure what `Substr` is, but +1 for out of range checking.
Marc
2010-08-17 19:26:40
@Marc: I occasionally confuse my C++ and C# libraries.
James Curran
2010-08-17 19:28:06
+1
A:
Since you don't want to use arrays, you could do an IndexOf('-') and then a substring.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Substring(0, index);
Or, for added fun, you could use String.Remove.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Remove(index);
fire.eagle
2010-08-17 19:23:28
+4
A:
Other possibility is
string xy = "01-India";
string xz = xy.Split('-')[0];
Ventus
2010-08-17 19:24:42
+1
A:
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.
Holystream
2010-08-17 19:25:32