Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting char into a java string for each N characters

Tags:

java

string

char

I have a java string, which has a variable length.

I need to put the piece "<br>" into the string, say each 10 characters.

For example this is my string:

`this is my string which I need to modify...I love stackoverlow:)` 

How can I obtain this string?:

`this is my<br> string wh<br>ich I nee<br>d to modif<br>y...I love<br> stackover<br>flow:)` 

Thanks

like image 602
Giancarlo Avatar asked Feb 11 '09 14:02

Giancarlo


People also ask

How do you add a char to a string in Java?

Using String concat (+) A simple solution to append a character to the end of a string is using the string concatenation operator (+) . This creates a new instance of the string, since strings in Java are immutable and cannot be modified.

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.

How do you declare a string of size n in Java?

To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];


1 Answers

Try:

String s = // long string s.replaceAll("(.{10})", "$1<br>"); 

EDIT: The above works... most of the time. I've been playing around with it and came across a problem: since it constructs a default Pattern internally it halts on newlines. to get around this you have to write it differently.

public static String insert(String text, String insert, int period) {     Pattern p = Pattern.compile("(.{" + period + "})", Pattern.DOTALL);     Matcher m = p.matcher(text);     return m.replaceAll("$1" + insert); } 

and the astute reader will pick up on another problem: you have to escape regex special characters (like "$1") in the replacement text or you'll get unpredictable results.

I also got curious and benchmarked this version against Jon's above. This one is slower by an order of magnitude (1000 replacements on a 60k file took 4.5 seconds with this, 400ms with his). Of the 4.5 seconds, only about 0.7 seconds was actually constructing the Pattern. Most of it was on the matching/replacement so it doesn't even ledn itself to that kind of optimization.

I normally prefer the less wordy solutions to things. After all, more code = more potential bugs. But in this case I must concede that Jon's version--which is really the naive implementation (I mean that in a good way)--is significantly better.

like image 92
cletus Avatar answered Sep 23 '22 09:09

cletus