Jump to content

changing char's of a String

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
8 replies to this topic

#1
zee_ola05

zee_ola05

    Newbie

  • Members
  • PipPip
  • 13 posts
String sample = "Java";

How do I change "Java" into, for example, "Jeva"?

change the 2nd char to 'e'?

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
i would convert the string into a char array

String text = "Java";

char[] letters = text.toCharArray();



then it's easy to change 1 char from the char array

letters[1]='e';

now just put the char array into the string

String temp="";

for(int i=0; i<letters.length(); i++){

  temp+=letters[i];

}

text = temp;


note: i don't have java on this computer. Did this without testing, might contain an error or 2

Edited by wim DC, 12 July 2009 - 02:22 AM.
forgot crucial code ;)


#3
zee_ola05

zee_ola05

    Newbie

  • Members
  • PipPip
  • 13 posts
Thanks oxano! it worked. I will send you a private message when I got other questions with JAVA. I hope that's ok. :D

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
no problem :)

#5
zee_ola05

zee_ola05

    Newbie

  • Members
  • PipPip
  • 13 posts
Another question.

How about the reverse, array of char to String?

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
isn't that the 3th part of my 1st post?

#7
zee_ola05

zee_ola05

    Newbie

  • Members
  • PipPip
  • 13 posts
ow. sorry. I didn't look at that before. Thanks!

#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
this might be another interesting way:
/**
 * Main.java
 *
 * @author www.javadb.com
 */
public class Main {
    
    /**
     * Converts an array of characters to a String
     */
    public void convertCharArrayToString() {
        
        char[] charArray = new char[] {'a', 'b', 'c'};
        String str = new String(charArray);
        
        System.out.println(str);
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().convertCharArrayToString();
    }
}
from Character array to String conversion - A Java Code Example

never did it that way, don't know if it works.

#9
zee_ola05

zee_ola05

    Newbie

  • Members
  • PipPip
  • 13 posts
That is better!