Jump to content

How to add a char into a string

- - - - -

  • Please log in to reply
3 replies to this topic

#1
abderrahim

abderrahim

    Newbie

  • Members
  • PipPip
  • 14 posts
  • Programming Language:C, Java, PHP, Perl, Pascal, Assembly, Haskell
  • Learning:C, Java, PHP, JavaScript, PL/SQL, Assembly, Haskell
Hi everybody, How can I add a chat into a string in specific place, why can't this method do it:
char[] word2;

String word;

word[j]=word2.charAt(i);
-------
or this
--------
String word;

String word2;

char c;

for (int i=0;i<word.length();i++)if (c=word.charAt(i)=='P'){word2.concat(valueOf(c));j++;}



---------- Post added 01-07-2012 at 12:21 AM ---------- Previous post was 01-06-2012 at 11:13 PM ----------

Any way I found the solution for anyone who would make the same mistake, Here it is, it should be
char[] word = {};

String word2 = " ";


word[j]=word2.charAt(i);


#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
String is immutable object - you can't change it after it's created. (To avoid major pitfalls and bugs)
also, you can't address any of the characters in the String like you access an array, this isn't C.

The "solution", you provided is incorrect. Because "word" is array of characters, not a String.
I think there isn't obvious solution, but maybe the shortest way goes like this:

String word = "Hello";
String word2 = word.substring(0, 1)+"a"+word.substring(2); 

word2 is set to "Hallo".
.

#3
abderrahim

abderrahim

    Newbie

  • Members
  • PipPip
  • 14 posts
  • Programming Language:C, Java, PHP, Perl, Pascal, Assembly, Haskell
  • Learning:C, Java, PHP, JavaScript, PL/SQL, Assembly, Haskell
Ok Sinipull, thank you so much, I think I got it.

#4
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
How about using a StringBuilder object?


StringBuilder sb = new StringBuilder("abcdfg");

sb.insert(4, 'e');

System.out.println(sb.toString());





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users