0

How do I split the string into a string array.

My string looks like this

string orgString = "1234-|@$@|-George,Michael -$@%@$-65489-|@$@|-Lawrence,  Steve J  -$@%@$-7897954-|@$@|-Oliver Mike  -$@%@$-56465-|@$@|-Waldimir Tursoky";

Now I want my string array to store name and number along with -|@$@|-

I tried the following code

string[] strArray = orgString.Split(new string[] {"-$@%@$-"}, StringSplitOptions.RemoveEmptyEntries);

My output looks like this:

"1234-|@$@|-George,Michael "

But my desired output is (name first, number last)

"George,Michael -|@$@|-1234"

How can i achieve this in C#?

4
  • 1
    Step #1 is to use/show compiling C# code.. Commented Sep 24, 2018 at 19:06
  • You can use split on hyphen '-' instead, then you have the chance to rearrange the strings. Commented Sep 24, 2018 at 19:09
  • 2
    Sounds like regex is more suitable to extract these values Commented Sep 24, 2018 at 19:11
  • @RufusL updated my code.It will compile now Commented Sep 24, 2018 at 19:14

2 Answers 2

2

Just swap parts in the resulting string :

string orgString = "1234-|@$@|-George,Michael -$@%@$-65489-|@$@|-Lawrence,  Steve J  -$@%@$-7897954-|@$@|-Oliver Mike  -$@%@$-56465-|@$@|-Waldimir Tursoky";
string[] resultingList = orgString.Split(new string[] {"-$@%@$-"}, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Split(new string[] {"-|@$@|-"}, StringSplitOptions.RemoveEmptyEntries).Aggregate((x11,y)=>{return y+" -|@$@|- "+x11;})).ToArray();
foreach(string result in resultingList)
{
    Console.WriteLine(result);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I appreciate it. Cant we have it in the string array instead of var.?
@Santosh yes, but you will need to add cast in that case.
@Santosh I have changed my answer
1

You can split again and then recombine

string outerDivider = "-$@%@$-";
string innerDivider = "-|@$@|-";

var results = orgString
    // Split by outer divider
    .Split(new string[] { outerDivider }, StringSplitOptions.RemoveEmptyEntries)
    // Then for each of the results, split again on the inner divider
    .Select(x => x.Split(new string[] { innerDivider }, StringSplitOptions.RemoveEmptyEntries))
    // Swap the order of elements around the inner divider and recombine into a string
    .Select(x => string.Join(innerDivider, x[1], x[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.