2015-01-13 47 views

回答

7

好吧,如果你有兴趣在一个面露正则表达式: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? 
+2

你刚刚救了我一些打字和调试:) –

+1

@MarkoTopolnik - 不是最好的解决方案。但它会工作:) – TheLostMind

+0

完全谢谢:) – Megaetron

3

使用String.substring

main = main.substring(main.indexOf("/") + 1) 
     + "/" 
     + main.substring(0, main.indexOf("/")) ; 
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]; 

当然,你也必须执行一些错误处理时,有没有斜线等..

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 
} 
+0

你不必在'split()'这里指定* limit * :) – TheLostMind

0

你也可以使用的StringTokenizer拆分的字符串中。

String main =“hello/bye”; StringTokenizer st = new StringTokenizer(main,“\”);

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

String newMain = part2 +“\”+ part1;

相关问题