如何围绕第二个单词包装标签?

时间:2014-02-24 09:23:44

标签: c# asp.net tags

我有一个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 <span>the</span> the journal

正如你所看到的,我无法从第二个太空角色开始。我怎么能这样做?

4 个答案:

答案 0 :(得分: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 );
    }
}

答案 1 :(得分:1)

尝试不同的方法:

    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]);

答案 2 :(得分:1)

做这样的事情:

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

答案 3 :(得分:0)

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

}

对于更一般的用法,我会添加第二个参数来确定包围范围的单词的索引。

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