
Signature
Steve W. Jackson
Montgomery, Alabama
> Do you know the actual position of the character in question? If so,
> look to the charAt(int) method. It's zero-based, naturally, so the
> number should range from zero to length()-1. If you don't know the
> actual position, you can get it with indexOf(char) that returns int. In
> either case, you can create the new string with combinations of those
> methods and substring.
Yupe, the actual position of the character is known. But if it's in the
middle, u have right and left leftovers?
Example:
String test = "0123456789";
and I want to change "5" into "a", like "01234a6789";
How do you take care of it?
I was thinking of keeping the "01234" and "6789" as 2 separate strings, and
adding them together by
test = "01234" + "a" + "6789";
But I find that it's a bit clumsy......any better ways?........
RC - 09 Mar 2004 21:24 GMT
> Yupe, the actual position of the character is known. But if it's in the
> middle, u have right and left leftovers?
[quoted text clipped - 11 lines]
>
> But I find that it's a bit clumsy......any better ways?........
You can do
char[] c = test.toCharArray();
c[5] = 'a';
String s = new String(c);
test = s;
Steve W. Jackson - 10 Mar 2004 17:41 GMT
>:> Do you know the actual position of the character in question? If so,
>:> look to the charAt(int) method. It's zero-based, naturally, so the
[quoted text clipped - 18 lines]
>:
>:But I find that it's a bit clumsy......any better ways?........
As the other replies have indicated, there are numerous ways to go about
it. Just keep in mind that creating too many String objects can get
dangerous (depending on the nature of the overall code involved), since
each "change" of a String actually leaves an old String object available
for garbage collection and creates another new one. for instance, your
example above demonstrates a "bad way" to do it if used excessively.
You've got 3 literal String objects. In Sun's code, if not optimized
out, that would create a StringBuffer object with the "01234" part, then
append() the "a" to it, and append "6789" to that, and call its
toString() method to create the final String object with the
concatenated result. This isn't necessarily always universally bad --
just not something that you want to get into doing in excess, in tight
loops, in performance sensitive code, etc., etc., etc.
= Steve =

Signature
Steve W. Jackson
Montgomery, Alabama