akaysait
akaysait

Reputation: 3

how to replace some chars in the string with other chars by the user?

I wrote a text, and i want to change some chars to any other chars which the user will choosing them, I tried and couldn't find the correct answer, so please guide me. the code in the MyTest Class is:

public String replace(String input,char from,char to){
   String input2 ="";
   String input3="";
   this.input=input3;
   for(int i=0;i<input.length();i++){
       for(int j=0;j<input3.length();j++){
          if(input.charAt(i)==input3.charAt(j)){
              input2=input3.replace(from, to);
              System.out.println(input2);
          }
       }

   }
   return input2;
}

And the code in the Main Class:

System.out.println("please enter the new character: ");
   char c1 = scan.next().charAt(0);
   System.out.println("Please choose the letters that you want to change it which in the text:");
   String ltr = scan.next();
   obj1.convertChars(ltr, c1);

Upvotes: 0

Views: 131

Answers (3)

ramesh
ramesh

Reputation: 300

The question seemed a bit unclear. I hope you want a function like this: Call this function from the main function. Pass the string "abcde", 'a', 'x'. It will return you "xbcde".

public String replace(String inputStr, char from, char to){
    StringBuffer newString=new StringBuffer();
    for(int i=0;i<inputStr.length();i++){
        if(inputStr.charAt(i)==from){
            newString.append(to);
        }
        else{
            newString.append(inputStr.charAt(i));
        }
    }
    return newString.toString();
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

What you want to do shouldn't even be a method. Here's why:

public String replace(String input,char from,char to){
    return input.replace(from, to);
}

Thus kind of method adds no value - you should just call the replace() method of String directly.

Upvotes: 1

amit
amit

Reputation: 178451

(1) What you should do:

There is a simple method for what you are after: String#replace(char,char):

String replaced = myString.replace(from,to);

(2) Why your code fails:

Note you are iterating and trying to invoke replace() on input3, while it is an empty string! you never changed it! effectively your method do nothing (except assigning the instance variable input. Definetly not what you wanted.

(3) Also important: Strings in java are immutable

In java, String is immutable - so what you are doing is actually crating a new string with replaced characters, and NOT replacing the characters in the same string object!

Changing the String is not as simple, and should be avoided, but can be done using the reflection API.

Upvotes: 3

Related Questions