用双引号把每个单词括起来

本文关键字:单词括 起来 | 更新日期: 2023-09-27 17:51:00

我必须用c#写一个函数,它将用双引号包围每个单词。我想让它看起来像这样:

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

这是我到目前为止想出的代码,但它不工作:

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();
}

用双引号把每个单词括起来

这在某种程度上取决于你认为什么是'word',但你可以使用正则表达式:

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

这将匹配字符串中任何一个或多个'word'字符(在正则表达式上下文中包括字母,数字和下划线)的序列,并将其用双引号括起来。

要换行任何非空白字符序列,可以使用'S代替'w:

lblText.Text = Regex.Replace(lblText.Text, @"'S+", "'"$0'"")

它不工作,因为Replace没有改变它的参数。不使用包含所需值的变量test

您也可以使用Linq执行如下操作:

return String.Join(" ", txtTextText.Split(' ').Select( word => "'"" + word "'""));

变化:

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();
}

:

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

您没有对test字符串做任何事情。并且字符串在每次循环迭代时都被重置,它现在正在追加

坚持OPs方法:

string input ="It's going to be a fine day";
string[] words = input.Split(' ');
string result = String.Empty;
foreach (string word in words)
{
    result += String.Format("'"" + word + "'" ");
}

我在单词后面加了一个空格。

所以你的代码应该是这样的:
protected void btnSend_Click(object sender, EventArgs e)
{
    string test = String.Empty;
    string[] words = txtText.Text.Split(' ');
    foreach (string word in words)
    {
        test += String.Format("'"" + word + "'" ");
    }
    lblText.Text = test;
}

你可以在这里使用Linq:

 lblText.Text = String.Join(" ", txtText.Text.Split(' ').Select(x => "'"" + x + "'""));

如果您需要为每个单词添加单引号,请尝试这样做:

List<string> list = new List<string>();
int i = 0;
yourStringArray.ToList().ForEach(x => list.Add(string.Format("'{0}'", yourStringArray[i++])));

这应该足够了

string txtText = "this is a string";
string[] words = txtText.Split(' ');
txtText =  @"""" + string.Join(@"""", words) + @""""; 

输出
 "this"is"a"string"
protected void btnSend_Click(object sender, EventArgs e)
     {
            string input = "It's going to be a fine day";
            string[] words = input.Split(' ');
            StringBuilder sb = new StringBuilder();
            foreach (string word in words)
            {
                if (!string.IsNullOrEmpty(word))
                {
                    sb.Append("'"");
                    sb.Append(word);
                    sb.Append("'" ");
                }
            }
          lblText.Text = sb.ToString();
  }