在每第四组单词之前和之后追加<i>标签

时间:2015-07-16 10:08:54

标签: c#

我编写了一个类似下面代码的方法

public string SplitLine(string input)
{
    var wordList = input.Split(' ');
    var sb = new StringBuilder();
    for (int index = 0; index < wordList.Length; index++)
    {
        sb.Append("<i>" + wordList[0]);
        if (index % 4 == 0 && index > 0)
            sb.Append("<br/></i>" + wordList[index]);
        else
            sb.Append(wordList[index] + ' ');
    }
    return sb.ToString();
}

基本上我希望它应该在每四个单词之后添加<i>标记和<br/>,例如

如果字符串包含“你好这是詹姆斯,我是专业的网页设计师。我喜欢网页设计”

然后输出应该像

<i>Hello this is james,</i><br/>
<i>i am a web designer</i><br/>
<i>by profession. I love</i><br/>
<i>web designing. </i>

3 个答案:

答案 0 :(得分:1)

Linq 解决方案(假设"i am a web designer"只是错误并且 正确的4个单词块应该是"i am a web")colud be:

  String text = 
    "Hello this is james, i am a web designer by profession. I love web designing";

  String result = String.Join(Environment.NewLine, text
    .Split(' ')
    .Select((item, index) => new {
        Text = item,
        Index = index / 4
      })
    .GroupBy(data => data.Index, data => data.Text)
    .Select(data => "<i>" + String.Join(" ", data) + "</i><br/>"));

result将包含

<i>Hello this is james,</i><br/>
<i>i am a web</i><br/>
<i>designer by profession. I</i><br/>
<i>love web designing</i><br/>

答案 1 :(得分:-1)

sb.Append("<i>"  + wordList[0] + ' ');
for (int index = 1; index < wordList.Length; index++)
{        
    if (index % 4 == 0)
        sb.Append("</i><br/>\n<i>" + wordList[index] + ' ');
    else
        sb.Append(wordList[index] + ' ');
}
sb.Append("</i><br/>");

如果还有其他小问题,请修复它们。否则,最重要的是学习

答案 2 :(得分:-1)

我喜欢这种类型的linq:

var input = "Hello this is james, i am a web designer by profession. I love web designing";
var inputList = input.Split(' ');
var nrOfLastItem = inputList.Length - 1;

var result = inputList.Select((word, nr) =>
                               ((nr % 4) == 0 ? "<i>" : "") 
                                  + word 
                                  + ((nr % 4) == 3 || (nr == nrOfLastItem) 
                                     ? "</i><br />" 
                                     : " "));

var output = String.Join("", result);

我确定你能猜到结果会是什么。