1

Strings:

string one = @"first%second";
string two = @"first%second%third";
string three = @"first%second%third%fourth";

I need to be able to separate everything that comes after the first '%' delimiter. I'd normally use split function:

string partofstring = one.Split('%').Last();

or

string partofstring = one.Split('%').[1];

However I need to be able to get:

string oneresult = @"second";
string tworesult = @"second%third";
string threresult = @"second%third%fourth";
3
  • 2
    string.Join("%", one.Split('%').Skip(1)) Commented Jan 6, 2020 at 9:41
  • string two = @"first%second%third"; var result = two.Split(new[] { '%' }, 2).Last(); Commented Jan 6, 2020 at 9:42
  • three.Split('%', 2)[1] Commented Jan 6, 2020 at 9:43

4 Answers 4

4

string.Split has an overload that allows you to specify the number of splits that you want to get back. Specifying 2 as the number of splits you will get an array with the element at index 0 that you can discard and the element at index 1 that is exactly the output requested

string three = @"first%second%third%fourth";
var result = three.Split(new char[] {'%'}, 2);
Console.WriteLine(result[1]); // ==> second%third%fourth
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

string partofstring = one.SubString(one.IndexOf('%'));

String.SubString returns a string starting from the specified position to the end of the string.

String.IndexOf returns the first index of the specified character in the string.

Comments

0

Either use a different overload of string.Split that allows you to specify the maximum number of items:

var newString = myString.Split('%', 2)[1];

Note if you're using .NET Framework, you will need to use a different overload:

var newString = three.Split(new[] { '%'}, 2)[1];

Or, calculate it yourself using IndexOf and Substring:

var newString = myString.Substring(myString.IndexOf('%') + 1);

2 Comments

the first result does not compile, this overload required Split(char[], int)
@styx Works fine if you're using .NET Core
0

I've improved the code snippet given by @Preciousbetine

var partofstring = two.IndexOf('%') < 0 ? string.Empty : two.Substring(two.IndexOf('%') + 1);

This will check if the string doesn't contain the key %.

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.