【问题标题】:How to wrap a tag around second word?如何在第二个单词周围加上标签?
【发布时间】:2014-02-24 09:23:43
【问题描述】:

我有一个 3-5 个单词的句子,我想用 span 包裹第二个单词。例如,如果句子是:

From the journal,我要转成From <span>the</span> journal

我正在使用以下方法:

public string cover2nd(string a)
{
    int pos = a.IndexOf(' ');
    return a.Substring(0, pos) + "<span class='color'>" + a.Substring(pos, pos + 1) +
           "</span>" + a.Substring(pos, a.Length - pos);
}

它会产生这个:

From &lt;span&gt;the&lt;/span&gt; the journal

如您所见,我无法让它从第二个空格字符开始。我该怎么做?

【问题讨论】:

    标签: c# asp.net tags


    【解决方案1】:

    在 Substring 的最后一个参数中,您需要从字符串中的下一个空格开始,而不是当前:

    public string cover2nd(string a) {
            int pos = a.IndexOf(' ');
            int posNext = a.IndexOf(' ',pos+1);
            return a.Substring(0, pos) + "<span class='color'>" + 
                   a.Substring(pos, posNext - pos) + "</span>" + a.Substring(posNext, a.Length - posNext );
        }
    }
    

    【讨论】:

    • 它变成了 From Jou,没用
    • @Kuzgun:只是测试它-稍微改变了最后一行。
    • 对于“来自期刊”它有效,但我还有一句“客户爱我们”,它变成了“客户爱我们我们”为什么会这样发生了吗?
    【解决方案2】:

    尝试不同的方法:

        String[] words = a.split(' ');
        StringBuilder sb = new StringBuilder();
        //check your sentence is not empty
        sb.append(words[0]);
        sb.append("<span class='color'>");
        sb.append(words[1]);
        sb.append("</span>");
        for(int i = 2; i<words.lenght; i++)
           sb.append(words[i]);
    

    【讨论】:

      【解决方案3】:

      做这样的事情:

      string text = "From the world";
      string[] array = text.Split(' ');
      array[1] = "<span class='color'>" + array[1] + "</span>";
      Console.WriteLine(string.Join(" ", array));
      

      【讨论】:

        【解决方案4】:
        public string cover2nd(string a)
        {
            if(a == null)
                return a;
        
            String[] words = a.Split(' ');
        
            if(words.Length < 2)
                return a;
        
            words[1] = "<span class='color'>" + words[1] + "</span>";
            return String.Join(' ', words);
        
        }
        

        对于更一般的用法,我将添加第二个参数来确定围绕其环绕 span 的单词的索引。

        public string coverItem(string a, int index)
        {
            if(a == null)
                return a;
        
            String[] words = a.Split(' ');
        
            if(words.Length < index)
                return a;
        
            words[index-1] = "<span class='color'>" + words[index-1] + "</span>";
            return String.Join(' ', words);
        }
        

        用法:

        string result = coverItem("From the journal", 2);
        

        【讨论】:

          猜你喜欢
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-15
          • 2017-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多