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"
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"
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"
+1, para una sola línea de código. –
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.
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 />");
}
}
Si yo tengo lo que quiere, se puede usar indexOf en un foreach y luego hacer algo así:
strTarget.Insert (strTarget.IndexOf (thirdcomma), "");
Creo que se puede crear algo de la lógica con que:
http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
Ademar
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> ";
}
}
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());
¿El último elemento 'mn: 33' será seguido por una coma', '? – sll
Gracias @sll ahora lo he editado. –
Solución perfecta ... – SanamShaikh
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();
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();
¿El último elemento 'mn: 33' será seguido por el símbolo de coma', '? – sll
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).
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
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
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 /> ");
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)));
No hay trabajo a domicilio, háganos saber qué ha intentado hasta ahora. – Zenwalker