如何检测字符串中的字母并切换它们?

Meg*_*ron 2 java string

如何检测字符串中的字母并切换它们?

我想过这样的事情......但这可能吗?

//For example:
String main = hello/bye;

if(main.contains("/")){
    //Then switch the letters before "/" with the letters after "/"
}else{
    //nothing
}
Run Code Online (Sandbox Code Playgroud)

The*_*ind 8

好吧,如果你对厚脸皮的正则表达感兴趣:P

public static void main(String[] args) {
        String s = "hello/bye"; 
        //if(s.contains("/")){ No need to check this
            System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
        //}

    }
Run Code Online (Sandbox Code Playgroud)

O/P:

bye/hello --> This is what you want right?
Run Code Online (Sandbox Code Playgroud)

  • 你刚给我保存了一些打字和调试:) (2认同)