0

I have a string "What is Facebook?.| A. Website B. Internet C. Social Network D. Game" How can I split and stored that string into 5 string separated in C# programming? I try to split with my code but the result I have just a mess.

What result I expect is that after split, I have 5 string variable separated like:

string A = "What is Facebook?"
string B = "A. Website"
string C = "B. Internet"
string D = "C. Social Network"
string E = "D. Game"

That is my code:

String value = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";
Char delimiter = '|';            
String[] substrings = value.Split(delimiter);
9
  • 4
    You need another split to split the second part. Have you tried anything for it? You can try with regex. Commented Nov 14, 2017 at 18:39
  • What precisely were you expecting as output of your "split"? Currently you'd only get two strings if you split on the '|'. Commented Nov 14, 2017 at 18:39
  • 2
    You may need to write a RegExp, like this one: ^(.*)\|.*(A\..*)(B\..*)(C\..*)(D\..*)$ Commented Nov 14, 2017 at 18:41
  • 1
    Sometime, no matter what you do, this split is going to fail. Commented Nov 14, 2017 at 18:41
  • 1
    If you can change the pattern.... Best do so.. Just add a | at the beginning of each section Commented Nov 14, 2017 at 18:44

3 Answers 3

1

You can split by \|?\s+(?=[A-Z]\.) :

string[] substrings = Regex.Split(value, @"\|?\s+(?=[A-Z]\.)");
Sign up to request clarification or add additional context in comments.

3 Comments

It's return nothing :((
I see. Your demo output fine. But not exactly my result I expect. You just print out only once string value, but what I need is output separate value like: string A = "What is Facebook?" and string B = "A. Website" and string C = "B.Social media" and etc.... Hope u can help me solve this problem. By the way, thanks so much Slai.
ahhh yeah yeah! I see! It's work fine. You use string.Join() method so the result output all value. If I just want each value separated, so I just do substring[0] and so on.... Thanks @Slai !!! U just save me from the hell ~~
1

If it were me, I would create a simple class that holds a question and the possible answers. This way, you can parse your string into a class which can do other fancy things, like display itself correctly, and could contain a property that indicates the index of the correct answer (so you can compare the user's selection with the correct index).

For example, this class has a static Parse method that takes in your string and returns an instance of the class. It also overrides ToString so that it displays the Question and Answers in a nice way:

public class QuestionAndAnswers
{
    public string Question { get; set; }
    public List<string> Answers { get; set; }
    public int IndexOfCorrectAnswer { get; set; }

    public static QuestionAndAnswers Parse(string qaInput)
    {
        if (qaInput == null) throw new ArgumentNullException(nameof(qaInput));

        var result = new QuestionAndAnswers();

        var parts = Regex.Split(qaInput, @"\|?\s+(?=[A-Z]\.)");

        result.Question = parts[0].TrimEnd('.');
        result.Answers = parts.Skip(1).ToList();

        return result;
    }

    public override string ToString()
    {
        return $"{Question}\n  {string.Join("\n  ", Answers)}";
    }
}

Then it can be use something like this:

private static void Main()
{
    var input = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";

    var qa = QuestionAndAnswers.Parse(input);

    Console.WriteLine(qa);

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output

enter image description here

3 Comments

Yes I see. Many developers (of course, genius !) here help me so much. But both of you just return one result that output only one string, when I really want the 5 string variable separated! Please help me ~~
The five strings are separated. One is stored in the qa.Question property, and the other 4 are stored in a List<string> in the qa.Answers property.
yaya I see ^^ I just try to run again and solved out the expect my output.
0

Like @Andrey Nasonov's comment said, this is a good application for regular expressions.

The following will get you your split, though I feel like there must be a better way to represent \s(\w.[\w\s]+ repeating four times.

Regex splitter = new Regex(@"(.*)\|\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)");
string[] results = splitter.Split(input);

stringA = results[0];
stringB = results[1];
stringC = results[2];
stringD = results[3];
stringE = results[4];

4 Comments

It's return an error "Index was outside the bounds of the array." at line string B = results[1] and corrupt the program without nothing result I expect.
I just double-checked and it runs as expected for me. Make sure you copied the Regex splitter = new ...... line verbatim. You might also check to see exactly what strings are in results after the split by using a breakpoint and the watch window (I'm assuming you're using Visual Studio).
Yes do I, but when it running, it make an error at line string B and corrupt everything. I also try to debug and sound like it out of range of array or something that I can't understand!
If it's giving you an out of range error on line B, that means results.length must equal 1, and it doesn't like you trying to access the second index (because that index doesn't exist). Sounds like it isn't splitting correctly.

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.