Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surround every word with double quotes

Tags:

string

c#

.net

I have to write function in C# which will surround every word with double quotes. I want it to look like this:

"Its" "Suposed" "To" "Be" "Like" "This"

Here is the code I've come up with so far, but its not working:

protected void btnSend_Click(object sender, EventArgs e)
{
    string[] words = txtText.Text.Split(' ');
    foreach (string word in words)
    {
        string test = word.Replace(word, '"' + word + '"');

    }
    lblText.Text = words.ToString();
}
like image 746
user3261123 Avatar asked Nov 29 '22 11:11

user3261123


1 Answers

Well it depends to some degree on what you consider a 'word', but you can use a regular expression:

lblText.Text = Regex.Replace(lblText.Text, @"\w+", "\"$0\"")

This will match any sequence of one or more 'word' characters (which in the context of regular expressions includes letters, digits, and underscores) in the string, and wrap it with double quotes.

To wrap any sequence of non-whitespace characters, you can use the \S instead of \w:

lblText.Text = Regex.Replace(lblText.Text, @"\S+", "\"$0\"")
like image 117
p.s.w.g Avatar answered Dec 07 '22 23:12

p.s.w.g