tags:

views:

88

answers:

7

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?

+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
+1  A: 

Something like this?

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

Other possibility is


string xy = "01-India";
string xz = xy.Split('-')[0];
Ventus
But there is an array.
schoetbi
+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
+1  A: 
string value = "01-India";

string part1 = value.Split('-')[0];
Basser