Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat the string sequence until it reaches a certain length in java

Tags:

java

string

I have two strings plainText and key. Now, if the plainText.length > key.length then i have to repeat the key until its the same length as that of plainText. here's an example:

plainText = "helloworld"
key="foobar"

hence the key should be increased to "foobarfoob".

One solution is to repeat the entire word and then remove the last characters until it reaches the same length as of plainText like "foobarfoobar" and then remove the characters "ar" .

Is there any better (or rather and Elegant) way to do this in java?

like image 770
md1hunox Avatar asked Mar 12 '26 00:03

md1hunox


1 Answers

Your solution seems reasonable, other than the way you remove the last characters - don't do it one at a time, just use substring or StringBuilder.setLength():

// Make sure we never have to expand...
StringBuilder builder = new StringBuilder(plainText.length() + key.length() - 1);
while (builder.length() < plainText.length()) {
    builder.append(key);
}
builder.setLength(plainText.length());
String result = builder.toString();

Or just change the append call to only get to the right size:

StringBuilder builder = new StringBuilder(plainText.length());
while (builder.length() < plainText.length()) {
    builder.append(key.substring(0, Math.min(key.length(),
                                        builder.length() - plainText.length()));
}
String result = builder.toString();

Personally I prefer the first - it's simpler.

like image 91
Jon Skeet Avatar answered Mar 14 '26 14:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!