Search code examples
c#stringtext-manipulation

Remove text between quotes


I have a program, in which you can input a string. But I want text between quotes " " to be removed.

Example:

in: Today is a very "nice" and hot day.

out: Today is a very "" and hot day.

        Console.WriteLine("Enter text: ");
        text = Console.ReadLine();

        int letter;
        string s = null;
        string s2 = null;
        for (s = 0; s < text.Length; letter++)
        {
            if (text[letter] != '"')
            {
                s = s + text[letter];
            }
            else if (text[letter] == '"')
            {

                s2 = s2 + letter;
                letter++;
                (text[letter] != '"')
                {
                    s2 = s2 + letter;
                    letter++;
                }
            }
        }

I don't know how to write the string without text between quotes to the console. I am not allowed to use a complex method like regex.


Solution

  • This should do the trick. It checks every character in the string for quotes. If it finds quotes then sets a quotesOpened flag as true, so it will ignore any subsequent character.

    When it encounters another quotes, it sets the flag to false, so it will resume copying the characters.

    Console.WriteLine("Enter text: ");
    text = Console.ReadLine();
    
    int letterIndex;
    string s2 = "";
    bool quotesOpened = false;
    for (letterIndex= 0; letterIndex< text.Length; letterIndex++)
    {
        if (text[letterIndex] == '"')
        {
            quotesOpened = !quotesOpened;
    
            s2 = s2 + text[letterIndex];
        }
        else 
        {
            if (!quotesOpened)
                s2 = s2 + text[letterIndex];
        }
    }
    

    Hope this helps!