Re: How to set a character of a String?




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

.



Relevant Pages

  • Re: How to add thousand separators
    ... First, this code is obsolete as written, because char is a dead data type and should not ... Note that both of these should be stored as string resources since they might need to be ... 18 digits for any reason. ... you have made a VERY SERIOUS DESIGN ERROR. ...
    (microsoft.public.vc.mfc)
  • Re: what is the best way of passing floats into a string
    ... I do not null-terminate as snprintf takes care of this (according to ... But the easiest way to determine the size needed to format a number, ... int length_of_representation(double n,const char* format){ ... I get a nice result of -10.000000 in my char * string. ...
    (comp.unix.programmer)
  • Re: weird problem
    ... I already told you that the comparison between an integer and a float ... to strcmpwhich expects a pointer to a string. ... And now a question about something else: why do you use floating ... int,float, char, etc. ...
    (comp.lang.c)
  • Re: why I can not write to the file after initialize the MFC in a service program
    ... you don't use char, an obsolete data type ... Why do you need an intermedate buffer to write literal strings anyway? ... For example, if AfxWinInit fails, you copy a 45-character string into a ... So you are going to try to initialize MFC EACH TIME THROUGH THE LOOP? ...
    (microsoft.public.vc.mfc)
  • Re: why I can not write to the file after initialize the MFC in a service program
    ... you don't use char, an obsolete data type ... Why do you need an intermedate buffer to write literal strings anyway? ... For example, if AfxWinInit fails, you copy a 45-character string into a ... So you are going to try to initialize MFC EACH TIME THROUGH THE LOOP? ...
    (microsoft.public.vc.mfc)