Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 663
Jolek111 Avatar asked Jan 21 '16 10:01

Jolek111


2 Answers

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!

like image 172
GigiSan Avatar answered Oct 02 '22 07:10

GigiSan


A take without regular expressions, which I like better, but okay:

string input = "abc\"def\"ghi";
string output = input;

int firstQuoteIndex = input.IndexOf("\"");

if (firstQuoteIndex >= 0)
{
    int secondQuoteIndex = input.IndexOf("\"", firstQuoteIndex + 1);

    if (secondQuoteIndex >= 0)
    {
        output = input.Substring(0, firstQuoteIndex + 1) + input.Substring(secondQuoteIndex);
    }
}

Console.WriteLine(output);

What it does:

  • It searches for the first occurrence of "
  • Then it searches for the second occurrence of "
  • Then it takes the first part, including the first " and the second part, including the second "

You could improve this yourself by searching until the end of the string and replace all occurrences. You have to remember the new 'first index' you have to search on.

like image 45
Patrick Hofman Avatar answered Oct 02 '22 09:10

Patrick Hofman