Home > other >  How to replace characters of a string with characters of another string in java
How to replace characters of a string with characters of another string in java

Time:12-13

How to replace the specific characters of a string with characters of another string in java.

For example: Input strings are like String str1 = 00*000/00;

String str2 = Hello1;

Result should be like below string

String result = He*llo/10

I tried using replace method and changing string to char and iterate but couldn’t get expected result.please help

For example: Input strings are like

String str1=00*000/00

String str2=Hello1

Result should be like below string

String result = He*llo/10

CodePudding user response:

java string replace() method is used to replace character to another character or string.The syntax for replace method is string_name.replace(old_string,new_string)

CodePudding user response:

Watch out, strings in Java are immutable.

String s = "ABC";
s.replace('A','C');
System.out.println(s);

will still print ABC.

String s = "ABC";
s=s.replace('A','C');
System.out.println(s);

Only this will print CBC.

https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/String.html#replace(char,char)

CodePudding user response:

If I understand your question correctly, you are looking for something that will convert some characters with another from second string. I thing that code would be quite useful without searching and using another libraries.

var str1 = "00*000/00";
var str2 = "Hello1";
var index = 0;
char[] newChars = new char[str1.length()];
char[] chars1 = str1.toCharArray();
for (var i = 0; i < chars1.length; i  ) {
    char c1 = chars1[i];
    char[] chars2 = str2.toCharArray();
    if (index >= chars2.length || c1 != '0') {
        newChars[i] = c1;
        continue;
    }
    char c2 = chars2[index];
    newChars[i] = c2;
    index  ;
}
String result = String.copyValueOf(newChars);
System.out.println(result);
  • Related