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 whol开发者_开发知识库e 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
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.
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.
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();
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
).
精彩评论