2

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?

1
  • FYI, your question has nothing to do with ASP.NET or C#. It's purely a .NET question, as the System.String type is part of .NET. Commented Aug 17, 2010 at 19:29

7 Answers 7

4

Other possibility is


string xy = "01-India";
string xz = xy.Split('-')[0];
Sign up to request clarification or add additional context in comments.

Comments

4

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('-'))

Comments

2
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
   prefix = str.SubString(0,pos);

2 Comments

Not sure what Substr is, but +1 for out of range checking.
@Marc: I occasionally confuse my C++ and C# libraries.
2
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.

Comments

2

Something like this?

var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));

Comments

1

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);

Comments

0
string value = "01-India";

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.