Hi, I would like to know how to set a character of an String object.
It's just like the opposite of charAt() method which returns the char
at a given position.
TIA
heysc0tt@gmail.com - 31 Oct 2006 00:07 GMT
> Hi, I would like to know how to set a character of an String object.
> It's just like the opposite of charAt() method which returns the char
> at a given position.
You could either get the prefix and suffix subsequences and put the
new char in the middle as such:
index i = 1;
String abc = "abc";
String adc = abc.substring(0, i) + "d" + abc.substring(i+1,
abc.length);
This is untested though and may throw IndexOutOfBounds if the index is
= length.
Or you could put this string in a StringBuffer and use its
setCharAt(int index, char ch) method.
index i = 1;
String abc = "abc";
StringBuffer abcBuffer = new StringBuffer(abc);
abcBuffer.setCharAt(i, 'd');
String adc = abcBuffer.toString();
There may be other ways to solve this, but these seemed like fairly
simple ways to do it, the second being simpler/safer it seems.
Scott
Thomas Fritsch - 31 Oct 2006 00:14 GMT
> Hi, I would like to know how to set a character of an String object.
> It's just like the opposite of charAt() method which returns the char
> at a given position.
You can't, because String is designed to be immutable.
You should use StringBuffer (which is like a mutable String). It has a
setCharAt(...) method.
There are methods/constructors to convert a StringBuffer to String and v.v.

Signature
Thomas
Thomas Schodt - 31 Oct 2006 00:15 GMT
> Hi, I would like to know how to set a character of an String object.
> It's just like the opposite of charAt() method which returns the char
> at a given position.
A String is immutable.
Use StringBuffer to create a new String.
Hal Rosser - 31 Oct 2006 02:06 GMT
> Hi, I would like to know how to set a character of an String object.
> It's just like the opposite of charAt() method which returns the char
> at a given position.
Are you talking about the indexOf("stringtoFind") method of the String
object?
its closest to the opposite of charAt(n) I casn think of.
HTH
Hal
Jeffrey Schwab - 31 Oct 2006 14:19 GMT
> Hi, I would like to know how to set a character of an String object.
> It's just like the opposite of charAt() method which returns the char
> at a given position.
No can do. You can construct a new String like this:
package cljp;
import java.io.PrintWriter;
public class Main {
private static PrintWriter out = new PrintWriter(System.out, true);
private static String replaceCharAt(String s, int index, char c) {
StringBuilder b = new StringBuilder(s);
b.setCharAt(index, c);
return b.toString();
}
public static void main(String[] args) {
String s = "abc";
out.println(s); // abc
s = replaceCharAt(s, 1, 'Q');
out.println(s); // aQc
}
}