2011-10-18 13 views
7

tengo una cadena comoAgregar línea después de 3 comas

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

Quiero añadir salto de línea después de 3 comas cada

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

No hay trabajo a domicilio, háganos saber qué ha intentado hasta ahora. – Zenwalker

Respuesta

4

Creo for bucle sería la solución más sencilla y clara pero es interesante hacerlo usando 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" 
+0

+1, para una sola línea de código. –

0

de mi programación muy limitada knowledg e, usaría un int para contar cuántos nombres se han escrito. (int nombreCount = 0). Cada vez que escribía un nombre, incrementaba el contador si era menos de 3, de lo contrario colocaría un salto de línea.

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 />"); 
    } 
} 
+2

su código no dará la salida que él quiere, por favor revise una vez. –

+0

El conjunto de resultados final debe contener símbolos de coma ',' – sll

+0

Vaya, se olvidó de las comas. La respuesta de @ skk es mejor que la mía. – Dmitriy

0

probar este ..

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> "; 
       } 
      } 
2

Usar la siguiente parte de código, no tendrán ningún problema.

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++; 
      } 

EDIT:

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

¿El último elemento 'mn: 33' será seguido por una coma', '? – sll

+0

Gracias @sll ahora lo he editado. –

+0

Solución perfecta ... – SanamShaikh

1

Lo mejor que puedo hacer con una solución LINQ:

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

Esto le dará a su salida requerida:

 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(); 
+0

¿El último elemento 'mn: 33' será seguido por el símbolo de coma', '? – sll

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

Eso es hacerlo con "una línea" de LINQ. Aunque no estoy muy seguro de si eso es realmente deseable teniendo en cuenta que probablemente sea bastante difícil para otro desarrollador entender lo que está sucediendo aquí a primera vista (especialmente si no tienes mucha experiencia con LINQ y especialmente con su función GroupBy).

+0

Parece que tiene un error tipográfico en la variable 'spliterAfter' ya que se utiliza en la consulta LINQ como' splitAfter', también he consultado su consulta y he obtenido '" tom: 1, john: 3, timmy: 5, cid: 8, ad: 88, hid: 99, mn: 33 "' en la variable 'x', tiene el mismo aspecto que la cadena de entrada, ¿ha verificado la consulta? – sll

+0

Ah sí, debería ser "split After" por supuesto. ¡Gracias por hacérmelo saber! Y sí, el divisor estaba mal (dividir por "," no produce ningún resultado porque no hay "," en la cadena, el divisor debe ser ","). – chrischu

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 /> "); 
1

Como otra opción (aunque el enfoque de bucle for será más performante, me gusta la forma en definitiva se trata),

asumiendo un método de extensión como éste:

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

que se rompe un IEnumerable<T> en un IEnumerable<IEnumerable<T>>, puede usar lo siguiente:

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