Home > Software engineering >  Replace all Occurances of '-' inside the string by '>'
Replace all Occurances of '-' inside the string by '>'

Time:05-10

public class Main {
    public static void main(String[] args) {
        String s = "abc-def-ghi-jkl-mno";
        System.out.println(s);
        s.replaceAll("\\-", ">");
        System.out.println(s);
    }
}

I need to replace all occurances of the character '-' inside the string with '>' how do i do it? I have tried s.replaceAll("-",">"); and s.replaceAll(Pattern.quote("-"), ">"); but it isn't working

CodePudding user response:

Change you code to this, and will work:

public static void main(String[] args) {
    String s = "abc-def-ghi-jkl-mno";
    System.out.println(s);
    s = s.replaceAll("\\-", ">");
    System.out.println(s);
}

Comment: Re-assign variable 's' with the result from 's.replaceAll("\-", ">");'.

CodePudding user response:

public static void main(String[] args) {
    String str = "abc-def-ghi-jkl-mno";
    System.out.println(str);
    //s.replaceAll("\\-", ">");
    String s = str.replaceAll("-",">");
    System.out.println(s);
}

CodePudding user response:

You are printing the old text value, make the text value equal to the new value after modification as follows:

public class Main {
    public static void main(String[] args) {
        String s = "abc-def-ghi-jkl-mno";
        System.out.println(s);
        s= s.replaceAll("\\-", ">");
        System.out.println(s);
    }
}
  • Related