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

时间:2015-01-13 13:38:57

标签: java string

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

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

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

if(main.contains("/")){
    //Then switch the letters before "/" with the letters after "/"
}else{
    //nothing
}

5 个答案:

答案 0 :(得分: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
        //}

    }

O / P:

bye/hello --> This is what you want right?

答案 1 :(得分:3)

使用String.substring

main = main.substring(main.indexOf("/") + 1)
       + "/"
       + main.substring(0, main.indexOf("/")) ;

答案 2 :(得分:3)

您可以使用String.split,例如

String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.

String newString = splitUp[1] + "/" + splitUp[0];

当然,如果没有斜杠等,你还必须实现一些错误处理。

答案 3 :(得分:0)

你可以使用string.split(分隔符,限制)

限制:可选。一个整数,指定拆分数,拆分限制后的项目将不包含在数组

String main ="hello/bye";
if(main.contains("/")){
    //Then switch the letters before "/" with the letters after "/"
    String[] parts  = main.split("/",1);

    main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
    //nothing
}

答案 4 :(得分:0)

您也可以使用StringTokenizer来分割字符串。

String main =" hello / bye&#34 ;; StringTokenizer st = new StringTokenizer(main," \");

String part1 = st.nextToken(); String part2 = st.nextToken();

String newMain = part2 +" \" + part1;