Re: How to set a character of a String?
- From: heysc0tt@xxxxxxxxx
- Date: 30 Oct 2006 15:07:09 -0800
On Oct 30, 2:34 pm, "Neroku" <n37...@xxxxxxxxx> wrote:
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
.
- References:
- How to set a character of a String?
- From: Neroku
- How to set a character of a String?
- Prev by Date: Re: Rationale behind constructor call chain... ( and comparison with C++)
- Next by Date: Re: How to set a character of a String?
- Previous by thread: How to set a character of a String?
- Next by thread: Re: How to set a character of a String?
- Index(es):
Relevant Pages
|