在3个逗号后添加换行符

时间:2011-10-18 09:55:33

标签: c# linq

我有一个像

这样的字符串
"tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33"

我想在每个3个逗号之后添加换行符

"tom: 1, john: 3, timmy: 5, </br> cid: 8, ad: 88, hid: 99, </br> mn: 33"

11 个答案:

答案 0 :(得分:4)

我相信for循环将是最简单明了的解决方案,但使用LINQ来实现它很有趣:

string input = "tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
char delimiter = ',';
var allParts = input.Split(delimiter);
string result = allParts.Select((item, index) => (index != 0 && (index+1) % 3 == 0)
                    ? item + delimiter + " </br>"
                    : index != allParts.Count() - 1 ? item + delimiter : item)
                    .Aggregate((i, j) => i + j);

// result (without a comma after the last item)
// "tom: 1, john: 3, timmy: 5, </br> cid: 8, ad: 88, hid: 99, </br> mn: 33"

答案 1 :(得分:2)

使用以下代码部分,它将正常工作。

string input = "tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
            string[] parts = input.Split(','); 
            StringBuilder result = new StringBuilder();
            int i = 1;
            while(i <= parts.Length) 
            {
                result.Append(parts[i-1] + ","); 
                if (i % 3 == 0)
                {
                    result.Append("<br />");
                }
                i++;
            }

编辑:

   result = result.Remove(result.ToString().LastIndexOf(','), 1);
   MessageBox.Show(result.ToString());

答案 2 :(得分:2)

string line ="tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
Regex regex = new Regex(@"(\w+?:\s+\d+,\s){3}");
string result = regex.Replace(line, "$&<br /> ");

答案 3 :(得分:1)

我能用LINQ解决方案做到最好:

    var count = 0;
    input.Aggregate(
        new StringBuilder(),
        (sb, ch) =>
        {
            sb.Append(ch);
            if (ch == ',' && ++count % 3 == 0) sb.Append(" </br>");
            return sb;
        }).ToString();

答案 4 :(得分:1)

string splitter = ", ";
string newLine = "<br/>";
int splitAfter = 3;
string s = "tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
string x = 
   s.Split(new[]{splitter}, StringSplitOptions.None) // Split
    // Make each string entry into a Tuple containing the string itself 
    // and an integer key declaring into which group it falls
    .Select((v, i) => 
       new Tuple<int, string>((int) Math.Floor((double) i/splitAfter), v)) 
    // Group by the key created in the line above
    .GroupBy(kvp => kvp.Item1)
    // Since the key is not needed any more select only the string value
    .Select(g => g.Select(kvp => kvp.Item2) 
    // Join the groups 
    // (in your example each group is a collection of 3 elements)
    .Aggregate((a, b) => a + splitter + b)) 
    // Join all the groups and add a new line in between
    .Aggregate((a, b) => a + splitter + newLine + b); 

这是用LINQ的“一行”来做的。虽然我不太确定这是否真的可取,因为考虑到其他开发人员可能很难理解乍看之下发生的事情(特别是如果你对LINQ及其GroupBy函数没有多少经验)。 / p>

答案 5 :(得分:1)

作为另一种选择(虽然for循环方法会更高效,但我喜欢它有多短),

假设像这样的扩展方法:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkSize)
{
    return source.Where((x,i) => i % chunkSize == 0).Select((x,i) => source.Skip(i * chunkSize).Take(chunkSize));
}

IEnumerable<T>分成IEnumerable<IEnumerable<T>>,您可以使用以下内容:

var s = "tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
var result = string.Join(", </br>", s.Split(',').Split(3).Select(x => string.Join(",", x)));

答案 6 :(得分:0)

从我非常有限的编程知识,我将使用int来计算已写入的名称数量。 (int nameCount = 0)。每次我写一个名字,如果它小于3,我会增加计数器,否则我会放置一个换行符。

答案 7 :(得分:0)

string [] parts = yourString.Split(',');
StringBuilder result = new StringBuilder();

for(int i = 0; i < parts.Length; i++)
{
  result.Append(parts[i]);
  if(i % 3 == 0)
  {
    result.Append("<br />");
  }
}

答案 8 :(得分:0)

如果我得到你想要的东西,你可以在foreach中使用indexof然后做类似的事情:

strTarget.Insert(strTarget.IndexOf(thirdcomma),“”);

我认为你可以创建一些逻辑:

http://msdn.microsoft.com/en-us/library/k8b1470s.aspx

ADEMAR

答案 9 :(得分:0)

试试这个..

 string[] split = textBox1.Text.Split(',');
             int count =0;
             for (int i = 0; i < split.Length; i++)
             {
                 count+=1;
                 if (i < split.Length - 1)
                 {
                     textBox2.Text += split.GetValue(i) + ",";
                 }
                 else
                 {
                     textBox2.Text += split.GetValue(i);
                 }
                 if (count == 3)
                 {
                     count = 0;
                     textBox2.Text += " </br> ";
                 }
             }

答案 10 :(得分:0)

这将为您提供所需的输出:

        string combinedValues = "tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33";
        string[] separatedValues = combinedValues.Split(',');
        for (int i = 3; i < separatedValues.Count(); i = i + 3)
        {
            separatedValues[i] =  @"<br />" + separatedValues[i];
        }
        StringBuilder sb = new StringBuilder();
        foreach (string value in separatedValues)
        {
            sb.Append(value);
            sb.Append(@",");
        }
        string combinedValuesWithBreak = sb.ToString();