Unknown user
Unknown user

Reputation: 45321

Chaining Strings in Java

let's say that I want to create a new string during a "for" loop,

The new string will be a change of an exsist string that will be change depanding a conditions and positions of the loop.

How can I insert to an exist string new chars?

I went through the whole method summary that relates to strings and didn't get my answer there.

Edit: Originaly I posted a java 4 link of methods by mistake. I use the newest version of java.

Thank you

Upvotes: 0

Views: 3808

Answers (4)

felixsigl
felixsigl

Reputation: 2920

use StringBuffer for performance reasons:

// new StringBuffer
StringBuffer buf = new StringBuffer("bla blub bla");

// insert string
buf.insert(9, " huhu ");

// append strings
buf.append(" at the end");

// Buffer to string
String result = buf.toString();

Upvotes: 2

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298938

Either use a StringBuilder or String.concat(String)

Example:

StringBuilder sb = new StringBuilder();
Iterator<Integer> iterator =
    Arrays.asList(1, 2, 3, 4, 5, 6, 7).iterator();
if(iterator.hasNext()){
    sb.append(iterator.next());
    while(iterator.hasNext()){
        sb.append(',').append(iterator.next());
    }
}
final String joined = sb.toString();

And about googling javadocs: Google will almost always return ancient 1.4 versions. if you search for keywords like the classname alone. Search for classname /6, e.g. StringBuilder /6 and you will get the current version.

Upvotes: 10

Michael Borgwardt
Michael Borgwardt

Reputation: 346307

How can I insert to an exist string new chars?

You can't. Java strings are designed to be immutable. You'll have to either use a mutable class like StringBuilder, or replace the original string with the new, modified version.

Upvotes: 3

Thomas
Thomas

Reputation: 88707

Try StringBuffer or StringBuilder. Do you have to code in Java 1.4?

You could also try this (though I highly recommend the StringBuilder/StringBuffer approach):

String s = "somestring";
s = s.substring(0, 4) + " " + s.substring(4); //result: "some string"

You'd need to find the indices for the substring() methods somehow (using indexOf or lastIndexOf).

Upvotes: 1

Related Questions