返回在 Java 中作为反向文本输入的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/501588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:40:20  来源:igfitidea点击:

Returning a string entered as reverse text in Java

javastring

提问by SaFruk

I'm trying to make a method that returns a string of words in opposite order.

我正在尝试制作一种以相反顺序返回一串单词的方法。

IE/ "The rain in Spain falls mostly on the" would return: "the on mostly falls Spain in rain The"

IE/“西班牙的雨大部分落在”会返回:“西班牙的雨大部分落在”

For this I am not supposed to use any built in Java classes just basic Java.

为此,我不应该使用任何内置的 Java 类,而只是基本的 Java。

So far I have:

到目前为止,我有:

    lastSpace = stringIn.length(); 

    for (int i = stringIn.length() - 1; i >= 0; i--){
        chIn = stringIn.charAt(i);
        if (chIn == ' '){
            word = stringIn.substring(i + 1, lastSpace);
            stringOut.concat(word);
            lastS = i;
        }
    }
    word = stringIn.substring(0,lastSpace);
    stringOut.concat(word);

    return stringOut;

My problem is when stringOutis returned to its caller it always is a blank string.

我的问题是当stringOut返回给它的调用者时它总是一个空字符串。

Am I doing something wrong? Maybe my use of string.concat()?

难道我做错了什么?也许我的用途string.concat()

回答by Dave Ray

In Java, Strings are immutable, i.e. they can't be changed. concat() returns a new string with the concatenation. So you want something like this:

在 Java 中,字符串是不可变的,即它们不能改变。concat() 返回一个带有连接的新字符串。所以你想要这样的东西:

stringOut = stringOut.concat(word);

or

或者

stringOut += word

as Ray notes, there are more succinct ways to do this though.

正如 Ray 所指出的,有更简洁的方法可以做到这一点。

回答by John Nilsson

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.trim();
}

Only API used is String (which should be allowed when manipulating Strings...)

仅使用的 API 是字符串(在操作字符串时应该允许...)

回答by Tiago

You would do better if you use the indexOf method of String class, rather than that loop to find each space.

如果您使用 String 类的 indexOf 方法,而不是使用循环来查找每个空间,您会做得更好。

回答by Lawrence Dol

That's because you need to assign the return of concat to something:

那是因为您需要将 concat 的返回分配给某些东西:

stringOut=stringOut.concat(word)

Strings in Java (and .net) are immutable.

Java(和 .net)中的字符串是不可变的。

回答by shambhu

public String reverseString(String originalString)
     {
     String reverseString="";
     String substring[]=originalString.split(" ");// at least one space between this double                      //quotes

    for(int i=(substring.length-1);i>=0;i--)
        {
        reverseString = reverseString + substring[i];
        }

      return sreverseString;
     }

回答by Geo

I felt like coding , so here you go :

我想编码,所以你去吧:


import java.util.*;

class ReverseBuffer {
    private StringBuilder soFar;
    public ReverseBuffer() {
        soFar = new StringBuilder();
    }

    public void add(char ch) {
        soFar.append(ch);
    }

    public String getReversedString() {
        String str = soFar.toString();
        soFar.setLength(0);
        return str;
    }
}

public class Reverso {
    public static String[] getReversedWords(String sentence) {
        ArrayList < String > strings = new ArrayList < String >();
        ReverseBuffer rb = new ReverseBuffer();
        for(int i = 0;i < sentence.length();i++) {
            char current = sentence.charAt(i);
            if(current == ' ') {
                strings.add(rb.getReversedString());
            }
            else {
                rb.add(current);
            }
        }
        strings.add(rb.getReversedString());
        Collections.reverse(strings);
        return (String[])strings.toArray(new String[0]);
    }

    public static void main(String[] args) {
        String cSentence = "The rain in Spain falls mostly on the";
        String words[] = Reverso.getReversedWords(cSentence);
        for(String word : words) {
            System.out.println(word);
        }
    }
}

EDIT: had to call getReversedString once more after the loop.

编辑:必须在循环后再次调用 getReversedString 。

Hope this helps !

希望这可以帮助 !