Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method to change multiple strings having same charecter in Java?

I am developing an application where I have to transpose from one music scale to another.

For Example:

cdefgab as gabcdef

c as g, d as a, e as b, f as c, g as d, a as e b as f

using .replace("c","g").replace("d","a").replace("e","b")... ###

But the output is a error as when the first c is replaced as g , g is replaced by d

Following is the code:

    String tune = "cdef gabc";        
    System.out.println(""+tune.replace("c","g")
                                            .replace("d","a")
                                            .replace("g","d"));

Current Output: daef dabd

Required output: gaef dabg

I want the the first string 'c' to be as 'g' and not 'd'

like image 989
clem Avatar asked Aug 18 '26 22:08

clem


1 Answers

Try this instead

System.out.println(tune.replace("a", "\uFFFF")
                       .replace("d", "a")
                       .replace("g", "d")
                       .replace("c", "g")
                       .replace("f", "c")
                       .replace("b", "f")
                       .replace("e", "b")
                       .replace("\uFFFF", "e"));

note: \uFFFF is not a valid character by definition so it won't appear in a valid string.

like image 80
Peter Lawrey Avatar answered Aug 21 '26 12:08

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!