如何检测字符串中的字母并切换它们?
How to detect the letters in a String and switch them?
如何检测String中的字母并进行切换?
我想过类似的事情...但这可能吗?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
使用String.substring
:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
好吧,如果您对 厚脸皮 正则表达式感兴趣:P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "/")); // () is a capturing group. it captures everything inside the braces. and are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
您可以使用 String.split 例如
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[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
}
您也可以使用 StringTokenizer 来拆分字符串。
字符串主="hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
字符串第 1 部分 = st.nextToken();
字符串第 2 部分 = st.nextToken();
String newMain = part2 + "\" + part1;
如何检测String中的字母并进行切换?
我想过类似的事情...但这可能吗?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
使用String.substring
:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
好吧,如果您对 厚脸皮 正则表达式感兴趣:P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "/")); // () is a capturing group. it captures everything inside the braces. and are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
您可以使用 String.split 例如
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[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
}
您也可以使用 StringTokenizer 来拆分字符串。
字符串主="hello/bye"; StringTokenizer st = new StringTokenizer(main,"\");
字符串第 1 部分 = st.nextToken(); 字符串第 2 部分 = st.nextToken();
String newMain = part2 + "\" + part1;