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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With