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?
7 Answers
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
2 Comments
Marc
Not sure what
Substr is, but +1 for out of range checking.James Curran
@Marc: I occasionally confuse my C++ and C# libraries.
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);
System.Stringtype is part of .NET.