因此,我有一个名为x的字符串=“ Hello world”。我想通过某种方式使其翻转这两个单词,并显示“ world Hello”。我对循环或数组不是很好,显然是一个初学者。我可以通过拆分字符串来完成此操作吗?如果是这样,怎么办?如果没有,我该怎么办?帮助将不胜感激,谢谢!
1)将字符串分成空格的String
数组。
String myArray[] = x.split(" ");
2)使用与数组相反的单词创建新的字符串。
String newString = myArray[1] + " " + myArray[0];
使用StringBuilder
代替串联的奖励点。
String abc = "Hello world";
String cba = abc.replace( "Hello world", "world Hello" );
abc = "This is a longer string. Hello world. My String";
cba = abc.replace( "Hello world", "world Hello" );
如果需要,您也可以爆炸字符串:
String[] pieces = abc.split(" ");
for( int i=0; i<pieces.length-1; ++i )
if( pieces[i]=="Hello" && pieces[i+1]=="world" ) swap(pieces[i], pieces[i+1]);
您也可以通过许多其他方式来做到这一点。请注意大写。您可以在if语句中使用.toUpperCase(),然后使匹配的条件变为大写,但结果保留其原始大小写,以此类推。
这是解决方法:
import java.util.*;
public class ReverseWords {
public String reverseWords(String phrase) {
List<String> wordList = Arrays.asList(phrase.split("[ ]"));
Collections.reverse(wordList);
StringBuilder sbReverseString = new StringBuilder();
for(String word: wordList) {
sbReverseString.append(word + " ");
}
return sbReverseString.substring(0, sbReverseString.length() - 1);
}
}
上述解决方案是由我为Google Code Jam编写的,也在此处博客发布:Reverse Words - GCJ 2010
只需使用此方法,调用它并传递您想要分割的字符串
static String reverseWords(String str) {
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1) {
result = temp[i] + result;
} else {
result = " " + temp[i] + result;
}
}
return result;
}
根据您的确切要求,您可能希望分割成其他形式的空格(制表符,多个空格等):
static Pattern p = Pattern.compile("(\\S+)(\\s+)(\\S+)");
public String flipWords(String in)
{
Matcher m = p.matcher(in);
if (m.matches()) {
// reverse the groups we found
return m.group(3) + m.group(2) + m.group(1);
} else {
return in;
}
}
如果您想变得更复杂,请参见模式[C0]的文档
太多?
String input = "how is this";
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String result = "";
for(String word : words) {
if(!result.isEmpty()) {
result += " ";
}
result += word;
}
System.out.println(result);