Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Putting char into a java string for each N characters

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...