谁能告诉我如何编写一个Java程序来反转给定的句子?
例如,如果输入是:
“这是一个面试问题”
输出必须是:
“面试问题是这个”
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
ArrayUtils
和 StringUtils
,但这些都是简单的编写方法 - 只需几个循环)
用空格分割字符串,然后向后迭代以组装相反的句子。
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
只是与众不同:递归解决方案。不添加任何额外的空格。
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
我还将通过使用
split
来改进 \b
解决方案(这太明显了!)。
String[] parts = "Word boundary is better than space".split("\\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
只需将其按空格字符拆分为字符串数组,然后以相反的顺序循环数组并构造输出字符串。
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
java 的每一个无聊的部分:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
在 groovy 中它更具可读性:
"this is an interview question"
.split("\\s")
.reverse()
.join(' ')
我也尝试一下:这是一个使用堆栈和扫描仪的版本:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
可能是更好的方法..在某处看到了逻辑..这是我的代码,可以完成这项工作。
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
我认为你不应该使用任何图书馆.. 1)反转整个字符串 2)颠倒每个单词。
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
还没有人提到基于 Java 8 的普通解决方案,它与 Bozho 的 相同,但没有任何第三方库。所以这里是:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
请尝试以下解决方案,这对我有用。
public class reverseline {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="This is interview question";
String words[]=str.split(" ");
for(int i=words.length-1;i>=0;i--){
System.out.print(words[i]+" ");
}
}
}
在 StringTokenizer 被宣布为遗留之前,许多人使用 StringTokenizer 来实现这一点。我想我会把它留在这里。
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());
最短答案
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
List<String> reverseWord = Arrays.asList(words);
Collections.reverse(reverseWord);
Iterator itr = reverseWord.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
或
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
for (int i = words.length-1 ; i >= 0; i--) {
System.out.print(words[i] +" ");
}
}
}
这个解决方案非常有效,我们需要做的就是
拆分数组中的单词
将它们向后添加到列表中
如果是最后一个字符,请勿添加额外的空格
打印列表
public static void main(String[] args) {
String words= "Hello to this World";
String[]split= words.split(" ");
List<String> newList = new LinkedList<>();
//Put the strings from array in list but in reverse order, avoid adding spaces for the last word.
for(int i=split.length-1;i>=0;i--){
if(i==0)
newList.add(split[i]);
else
newList.add(split[i]+" ");
}
for(String s : newList){
System.out.print(s);
}
}