Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surround string with another string

Tags:

java

I there any utils method in Java that would enable me to surround a string with another string? Something like:

surround("hello","%");

which would return "%hello%"

I need just one method so the code would be nicer then adding prefix and suffix. Also I don't want to have a custom utils class if it's not necessary.

like image 657
Michal Krasny Avatar asked Nov 28 '22 14:11

Michal Krasny


2 Answers

No but you can always create a method to do this:

public String surround(String str, String surroundingStr) {

    StringBuffer buffer = new StringBuffer();
    buffer.append(surroundingStr).append(str).append(surroundingStr);

    return buffer.toString();
}  

You have another method of doing it but Do not do this if you want better performance:-

public String surround(String str, String surroundingStr){

    return surroundingStr + str + surroundingStr;
}  

Why not use the second method?

As we all know, Strings in Java are immutable. When you concatinate strings thrice, it creates two new string objects apart from your original strings str and surroundingStr. And so a total of 4 string objects are created:

1. str
2. surroundingStr  
3. surroundingStr + str
4. (surroundingStr + str) + surroundingStr  

And creating of objects do take time. So for long run, the second method will downgrade your performance in terms of space and time. So it's your choice what method is to be used.

Though this is not the case after java 1.4

as concatinating strings with + operator uses StringBuffer in the background. So using the second method is not a problem if your Java version is 1.4 or above. But still, if you wanna concatinate strings is a loop, be careful.

My suggestion:

Either use StringBuffer of StringBuilder.

like image 27
Aditya Singh Avatar answered Dec 11 '22 05:12

Aditya Singh


String.format can be used for this purpose:

String s = String.format("%%%s%%", "hello");

like image 167
maximus Avatar answered Dec 11 '22 05:12

maximus