1

how can I extract a part from string with "-" separated between the characters? for example, I want to extract "123" from "123-4567-9012" or extract "4567" from "123-4567-9012" or even 9012 from the same string

1
  • 1
    you van use Substring, or you can Split and get them with array.. Commented Dec 12, 2012 at 10:06

3 Answers 3

10

Just split on the - character and later you can access them. Use string.Split(char[])

string str  = "123-4567-9012";
string[] arr = str.Split('-');

it will result in:

arr[0] = "123";
arr[1] = "4567";
arr[2] = "9012"
Sign up to request clarification or add additional context in comments.

Comments

3

Probably more effective if you need only first occurrence:

var str = "123-4567-9012";
var substr = str.Substring(0, str.IndexOf('-'));

Comments

3

If you String.Split, you can break a string into separate parts, based on a delimter. For example, using:

var input = "123-4567-9012";
var parts = input.Split('-');
foreach(var part in parts)
  Console.WriteLine(part);

Will output:

123
4567
9012

You can do the opposite with String.Join- for example.

var result = String.Join("-", parts);
Console.WriteLine(result);

Will output:

123-4567-9012

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.