Add a place after every fourth character +

I have a text like this:

"A01 + B02 + C03 + D04 + E05 + F06 + G07 + H08 + I09 + J10 + K11 + L12 + M13 + N14 + O15 + P16"

I would like to add a space after every fourth β€œ+” sign.

This is because if the text is too long in the grid cell on my page, then it just turns off. So I'm going to just wrap the string before binding the data to the grid.

I played with several string methods, for example, getting IndexOf and adding space with Insert, or using StringBuilder to make a completely new string from the original, but I just can't get the final solution working.

Any help would be greatly appreciated. Thanks.

+6
source share
7 answers

You can use LINQ:

string input = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16"; string final = string.Join( "+", input .Split('+') .Select( (s, i) => (i>0 && i%4==0) ? " "+ s : s)); 
+6
source share

Use regex:

 Pattern pattern = Pattern.compile("([^+]*\\+){4}"); Matcher matcher = pattern.matcher(str); matcher.replaceAll("\1 "); 
+10
source share

You can simply use the word-wrap CSS property to break a line with a specific width ...

 td.longString { max-width: 150px; word-wrap: break-word; } 

Just set CssClass="longString" to the appropriate column.

+6
source share

simpler:

 input = Regex.Replace(input, @"((?:[\w_]+\+){4})", "$1 "); 
+3
source share
 string text = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16"; string[] parts = test.Split( '+' ); StringBuilder output = new StringBuilder( ); for( int i = 0; i < parts.Length; i++ ) { if( i%4 == 0 ) { output.Append( " " ); } output.Append( parts[ i ] + "+" ); } 
+2
source share

This is the first thing that comes to my mind. Not the most beautiful though.

 var str = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16"; var strings = str.Split(new [] {'+'}); var builder = new StringBuilder(strings[0]); for(var i = 1; i< strings.Length;i++) { builder.Append(i%4 == 0 ? "+ " : "+"); builder.Append(strings[i]); } 
+1
source share

Regular expressions are good and good, but once said

Some people, faced with a problem, think: "I know, I will use regular expressions." Now they have two problems.

How about this simple isntead solution:

  String testString = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16"; StringBuilder buffer = new StringBuilder(testString); int plusCount = 0; for (int i=0; i<buffer.length(); i++) { if (buffer.charAt(i) == '+') { plusCount++; if (plusCount == 4) { buffer.insert(i+1, ' '); i++; plusCount=0; } } } 
0
source share

All Articles