Surround string with another string - 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.

String.format can be used for this purpose:
String s = String.format("%%%s%%", "hello");

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.

Not that i know of, but as already commented, its a single line piece of code that you could write yourself.
private String SurroundWord(String word, String surround){
return surround + word + surround;
}
Do note that this will return a New String object and not edit the original string.

Create a new method:
public String surround(String s, String surr){
return surr+s+surr;
}

Tested the following and returns %hello%
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(surround("hello", "%"));
}
public static String surround(String s, String sign) {
return sign + s + sign;
}

StringUtils.wrap(str,wrapWith) is what you are looking for.
If apache common utils is already a part of dependency, then you can use it. Otherwise as others already mentioned. It's better to add to your base. Not a big deal
https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/StringUtils.java

Related

Return or Print StringBuilder? Java

I am a bit confused about the StringBuilder. It seems that when I print a StringBuilder, there it no need to add .toString() because it will automatically give me a string representation. However, when I return a StringBuilder object, I have to add the .toString(). Is that true? and why?
Also, I am bit confused about the following code:
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("India ");
System.out.println("string = " + str);
// append character to the StringBuilder
str.append('!');
// convert to string object and print it
System.out.println("After append = " + str.toString());
str = new StringBuilder("Hi ");
System.out.println("string = " + str);
// append integer to the StringBuilder
str.append(123);
// convert to string object and print it
System.out.println("After append = " + str.toString());
}
}
For the different println, sometimes this code use toString and some other times it didn't. Why? I tried deleting the toString and the results are the same. Is it still necessary to use toString in println?
Thanks so much for helping a newbie out!
When you print an object to a print stream, the String representation of that object will be printed, hence toString is invoked.
Some classes override Object#toString, amongst which StringBuilder does.
Hence explicitly invoking toString for StringBuilder is unnecessary.
On the other hand, other objects don't override toString. For instance, arrays.
When you print an array, unless using a utility such as Arrays.toString, you're getting the array's class type # its hash code, as opposed to a human-readable representation of its contents.
From the documentation:
Note that println() prints a string builder, as in:
System.out.println(sb);
because sb.toString() is called implicitly, as it is with any other object in a println() invocation.
If you try to append an object to a string like this : "string = " + str, the toString() method is implicitly called.
So no, it does not matter, if you specify it.
Also the toString() method itself (even when you are not append it to string) calls the toString() method.
Therefore System.out.println(str) and System.out.println(str.toString()) gives same result.
The first thing you should know about Java is that we work with objects and that all objects inherit methods from the class Object: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
This class has a toString() method and since every object inherits this method it can always be called on every object. When you do not override it, it usually returns the physical address of the object.
Like stated in other answers, whenever a string is expected in println for instance and you pass an object it automatically calls the method which requires an Object (note the capital, we are talking about the class Object here), it will then use the toString method on the object passed along as parameter. The reason you get the string you want is because StringBuilder overrides the toString() method for you.
When you in your own code want to pass the string in your StringBuilder you have two options. You can either pass StringBuilder.toString() or change the return type to Object or StringBuilder and call toString() when you actually need it.
Hope this clarifies why you can just pass the object instead of the string.

Connect multiple strings efficiently

I've got an interface IO, that offers two methods, void in(String in) and String out(). I've implemented that in a first, naive, version:
private String tmp="";
public void in(String in){
tmp=tmp+in;
}
public String out(){
return tmp;
}
I know this is an horrible implementation, if you have multiple, very long Strings. You need make a new String with length = tmp.length+in.length, copy tmp, copy in. And then repeat that again for evey inserted String. But what is an better implementation for that?
private List<String> tmp= new ArrayList<>() //maybe use an different list?
public void in(String in){
tmp.add(in);
}
public String out(){
return connect(tmp);
}
private String connect(List<String> l){
if(l.size()==1) return l.get(0);
List<String> half = new ArrayList<>();
for(int i=0;i<l.size();i+=2){
half.add(l.get(i)+l.get(i+1)); \\I have to check, if i+1 is valid, but this is just a draft ;)
}
return connect(half);
}
This is a bit better, it has to make the same number of String-connections, but the Strings are going to be smaller by averange. But it has an giant offset, and i'm not sure it's worth it. There schould be an easier option than this imho, too...
You may be looking for a StringBuilder.
private StringBuilder tmp = new StringBuilder();
public void in(String in) {
tmp.append(in);
}
public String out() {
return tmp.toString();
}
The standard library provides a class specifically for efficient string concatenation, the StringBuilder:
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Note that the compiler will actually desugar your string "additions" into expressions involving StringBuilders, and in a lot of simple/naïve cases it will also optimize the code to make use of the append() method instead of constantly creating new StringBuilders. In your case, however, it is definitely a good idea to explicitly use a StringBuilder.
As for your adventurous attempt at optimizing the concatenation, I honestly don't think you will notice any improvements over the naïve solution, and clean code is always preferable to "slightly faster code", unless clock cycles are extremely expensive.
From Java Doc:
If your text can change and will only be accessed from a single
thread, use a StringBuilder because StringBuilder is unsynchronized.
If your text can changes, and will be accessed from multiple threads,
use a StringBuffer because StringBuffer is synchronous.
In your case StringBuilder will work just fine.
The StringBuilder class should generally be used in preference to this
one, as it supports all of the same operations but it is faster, as it
performs no synchronization.
http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html

Clarification about the toString method within an ADT class

This is the modified toString function within the Complex ADT class that i'm trying to implement (My doubt is only regarding this function so I havent included the private variables declared before and the other functions) :
class ComplexCart implements Complex{
public String toString(){
if(image == 0) return (real + "");
}
}
Why can't we write the following?
if(imag == 0) return(real);
Why do we need to add the additional "" ?
since the return type is String, and real is integer type. alternatively you can use real.toString()
Since real is int type where as toString() method expects String to return.So you need add "";
+ is String concatenation operator here.
public String toString(){
if(image == 0) return (real + "");
}
In the above code if real is not of type String it's compile time error.
if it is of type String.No errorrs occures.
To make real as string you are writing real + "".
Then , Immediate question is Then how it's working with + "" ??
Here the Docs of String
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
As a side note:
concatenating with String is a bad idea.There are some identical and better ways to do it.
1)Integer.toString(intval);
2)String.valueOf(intval);
It's because you have to return a String from toString(), and presumably real is not a String. real + "" performs string concatenation (converting real to a String and concatenating it with the empty string; see JLS §15.18.1) and results in a String, which is why you can validly return it.
Note that you should consider using something like Integer.toString(real) over real + "" (see Integer.toString()).

toString java of arrays

I have several arrays in a class
I want to implement toString() to print all values.
How to do this?
public String var1[];
public int var2[];
public String var3[][];
public int var4[];
public int var5[][];
public String toString() {
for(String s : var1) {
System.out.println(s.toString());
}
return null;
}
That prints all var1[] content but how to print all?? Do I have to put a loop for every one of them?
You can use the Arrays.toString() static helper method as follows:
String lines[] = getInputArray();
System.out.println(java.util.Arrays.toString(lines));
I think what you are looking for is Arrays.deepToString()
Refer to this link for more details. It takes an array and calls toString() on every element.
First of all, it depends on the size of your arrays. You did not mention any size for each of it. Of course, we can use for each. The second question obviously, how to want to print them all in the screen. that is the matter.
In case, if you go with normal for loop [ex: for(int i=0;i<ar.length();i++)] in this case. You have to go by individual loop for each array.
If your array size is same for all. You can simply use one loop to iterate all of them to print it off.
Hint: don't forget to handle the ArrayOutofBound exception. You would need that :P
String someArray = new String[] {"1", "2"};
String toString = Arrays.asList(someArray).toString();
The code above will print out the toString in a more readable format:
[1, 2]
If you are using JDK 1.5, you can use:
String[] strings = { "ABC", "DEF" };
String s = Arrays.toString(strings);

get a string as a reference in java

So I want to be able to have a collection of mutable Strings in Java.
I have this test class to see the functionality of immutable Strings:
public class GetStringTest
{
private Vector<String> m_stringList;
public GetStringTest()
{
m_stringList = new Vector<String>();
m_stringList.add("zero");
m_stringList.add("one");
m_stringList.add("two");
m_stringList.add("three");
m_stringList.add("four");
m_stringList.add("five");
m_stringList.add("six");
}
public String getString(int index)
{
return m_stringList.get(index);
}
public String toString()
{
String str = "";
for (String item : m_stringList)
{
str += item + "\n";
}
return str;
}
public static void main(String[] args)
{
GetStringTest gst = new GetStringTest();
System.out.println("=== original content ===");
System.out.println(gst);
String strToChange = gst.getString(2); // "two"
strToChange = "eleventy-one";
System.out.println("=== with change ===");
System.out.println(gst);
}
}
The following is the output:
=== original content ===
zero
one
two
three
four
five
six
=== with change ===
zero
one
two
three
four
five
six
What can I do to store these Strings as mutable? I was thinking of having a StringObject class that would simply contain a reference to a String. Is this the best option?
StringBuilder is a mutable string representation.
A mutable sequence of characters.
It is the unsynchronized (and more efficient) version of StringBuffer
May I recommend you to use a StringBuffer.
From the API:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
Note that if you don't plan to use it in you're better off with a StringBuilder as it is unsynchronized and faster.
If you want to change (replace) a list element you could add
public String setString(int index,String str)
{
return m_stringList.set(index, str);
}
And call:
String strToChange = gst.setString(2,"eleventy-one");
instead of:
String strToChange = gst.getString(2); // "two"
strToChange = "eleventy-one";
Thats because your Vector holds a reference to an immutable String, the reference can be replaced by a another String, the String itself can't be changed.
Ther's not a reference copy in Java. You can do a new method to GetString class to set a new String to a determined index.
Example:
gst.changeString(index, "NewString");
changeString internally set reference to "NewString".

Categories

Resources