在Java中用Word反向字符串

时间:2012-02-02 00:03:12

标签: java string

我有以下代码逐字反转字符串,但我有一个问题,首先有人能指出如何使它更好的代码?第二,如何删除新字符串开头的空格。

String str = "hello brave new world";
tStr.reverseWordByWord(str)

public String reverseWordByWord(String str){
        int strLeng = str.length()-1;
        String reverse = "", temp = "";

        for(int i = 0; i <= strLeng; i++){
            temp += str.charAt(i);
            if((str.charAt(i) == ' ') || (i == strLeng)){
                for(int j = temp.length()-1; j >= 0; j--){
                    reverse += temp.charAt(j);
                    if((j == 0) && (i != strLeng))
                        reverse += " ";
                }
                temp = "";
            }
        }

        return reverse;
    }

此刻的短语变为:

  

olleh evarb wen dlrow

注意新字符串开头的空格。

37 个答案:

答案 0 :(得分:7)

不使用split函数代码如下:

public static void reverseSentance(String str) {
    StringBuilder revStr = new StringBuilder("");
    int end = str.length(); // substring takes the end index -1
    int counter = str.length()-1;
    for (int i = str.length()-1; i >= 0; i--) {     
        if (str.charAt(i) == ' ' || i == 0) {
            if (i != 0) {
                revStr.append(str.substring(i+1, end));
                revStr.append(" ");
            }
            else {
                revStr.append(str.substring(i,end));
            }
            end = counter;
        }
        counter--;
    }
    System.out.println(revStr);
}

答案 1 :(得分:5)

如果str =“快速的棕色狐狸跳过懒狗!”它将像“狗!懒散的跳过狐狸褐色快速回归”... ...

  private static String Reverse(String str) {
      char charArray[] = str.toCharArray();
    for (int i = 0; i <str.length(); i++){
        if(charArray[i] == ' ')
        return Reverse(str.substring(i + 1)) + str.substring(0, i) + " ";
    }

    return str + " ";
}

答案 2 :(得分:3)

以下是你如何做到的:

    StringBuilder result = new StringBuilder();
    StringTokenizer st = new StringTokenizer(input, " ");
    while (st.hasMoreTokens()) {
        StringBuilder thisToken = new StringBuilder(st.nextToken());
        result.append(thisToken.reverse() + " ");
    }
    String resultString = result.toString();

答案 3 :(得分:2)

我使用StringUtils的方法。在单元测试中。

@Test
public void testReversesWordsAndThenAllCharacters(){
    String sentence = "hello brave new world";
    String reversedWords = StringUtils.reverseDelimited(sentence, ' ');
    String reversedCharacters = StringUtils.reverse(reversedWords);
    assertEquals("olleh evarb wen dlrow", reversedCharacters);
}

如果静态导入StringUtils,可以将其内联到:

reverse(reverseDelimited("hello brave new world", ' '))

答案 4 :(得分:1)

这里有一个线程也在讨论这个问题。我认为使用正则表达式拆分的一个答案非常聪明。

https://codereview.stackexchange.com/questions/43838/reverse-a-string-word-by-word

public String reverseWordByWord(String s) {
  StringBuilder result = new StringBuilder();
  String[] words = sentence.split("\\s+");      
  for (int i = words.length - 1 ; 0 <= i; i--) {
    result.append(words[i]).append(' ');
  }
  return result.toString().trim();
}

答案 5 :(得分:1)

另一种解决方案。该解决方案就位。

字符串中的反向字(单词由一个或多个空格分隔),空格可以在单词之前,即句子开头的空格,结尾等等......就地解决它。

public class ReverseWordsInString {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    char[] sentence = "  Hi my name is person!".toCharArray();
    System.out.println(ReverseSentence(sentence));  

}
private static char[] ReverseSentence(char[] sentence)
{
    //Given: "Hi my name is person!"
    //produce: "iH ym eman si !nosrep"
    //the obvious naive solution: utilize stringtokenize to separate each word into its own array. reverse each word and insert space between each array print
    //better solution: drop stringtokenize and use a counter to count how many characters processed before space was hit. 
    //                 once space hit, then jump back swap characters between counter-1 and start position. O(1) Space

    if(sentence == null) return null;
    if(sentence.length == 1) return sentence;       

    int startPosition=0;
    int counter = 0;
    int sentenceLength = sentence.length-1;

    //Solution handles any amount of spaces before, between words etc...    

    while(counter <= sentenceLength)
    {
        if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
        {
            //swap from startPos to counter - 1
            //set start position to -1 and increment counter
            int begin = startPosition;

            int end;
            if(sentenceLength == counter)
            {
                end = counter;
            }
            else                
                end = counter -1;
            char tmp;

        //Reverse characters
            while(end >= begin){

                tmp = sentence[begin];
                sentence[begin] = sentence[end];
                sentence[end] = tmp;

                end--; begin++;

            }               

            startPosition = -1; //flag used to indicate we have no encountered a character of a string


        }

        else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
        {
            startPosition = counter;
        }

        counter++;  
    }

    return sentence;        
}

}

答案 6 :(得分:1)

删除起始空格字符的答案很简单,只需

return reverse.trim();

String.trim()返回字符串的副本,省略前导和尾随空格(从Javadoc文档中复制)。

对于你的整体问题,我做了这个样本:

String job = "This is a job interview question!";
StringBuilder sb = new StringBuilder(job);
String[] words = job.split(" ");
int i = 0;
for (String word : words) {
    words[i] = (new StringBuilder(word)).reverse().toString();
    i++;
}

System.out.println("job = " + job);
System.out.print("rev = ");
for (String word: words) {
    sb.append(new StringBuilder(word).toString());
    sb.append(" ");
}

String rev = sb.toString().trim();
System.out.println(rev);

,输出为:

job = This is a job interview question!
rev = sihT si a boj weivretni !noitseuq

如果您想更多地包含任何空格字符,例如制表符,换行符,换页符,请将split()参数更改为split("\\s"),因为\s是正则表达式字符类,体现了[\ t \ r \ n \ f]。注意你必须如何转义正则表达式的Java字符串表示中的反斜杠字符(这是split方法所期望的)。

答案 7 :(得分:1)

另一种不使用拆分方法的解决方案

    public static String reverseWordsWithoutSplit(String str) {
    StringBuffer buffer = new StringBuffer();
    int length = str.length();
    while(length >0) {
        int wordstart = length -1;
        while(wordstart >0 && str.charAt(wordstart) != ' '){
            wordstart--;
        }
        buffer.append(str.substring(wordstart==0?wordstart:wordstart+1, length));
        if(wordstart>0)
            buffer.append(" ");
        length = wordstart;
    }
    return buffer.toString();
}

答案 8 :(得分:1)

public static void reverseByWord(String s) {

        StringTokenizer token = new StringTokenizer(s);

        System.out.println(token.countTokens());
        Stack<String> stack = new Stack<String>();
        while (token.hasMoreElements()) {
            stack.push(token.nextElement().toString());
        }

        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

答案 9 :(得分:1)

如何在java中反转单词

public class ReverseString {

public static void main(String[] args) {
    String reverse = "";
    String original = new String("hidaya");

      for ( int i = original.length() - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.err.println("Orignal string is: "+original);
      System.out.println("Reverse string is: "+reverse);
    }
}

答案 10 :(得分:1)

public class StringReversers {

    public static void main(String[] args) {
        String s = new String(revStr("hello brave new world"));
        String st = new String(revWords("hello brave new world"));
        System.out.println(s);
        System.out.println(st);
    }

    public static String revStr(String s){
        StringBuilder sb = new StringBuilder();
        for (int i=s.length()-1; i>=0;i--){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }

    public static String revWords(String str) {
        StringBuilder sb = new StringBuilder();
        String revd = revStr(str);
        for (String s : revd.split(" ")){
            sb.append(revStr(s));
            sb.append(" ");
        }
        return sb.toString();
    }

}

答案 11 :(得分:1)

这是一种使用流行的UINT64 encodedID; (...) FullID fullID = Decode(encodedID); (...) encodedID = Encode(fullID); ()函数的编码技术,它可以在所有主要语言中使用,Java split(),可以完全控制字符串形式的字符,以及性能方面的Java toCharArray类(也可以在C#中使用)。

我认为与其他发布的答案相比,代码更容易理解

StringBuilder

提醒作者发布的要求 示例输入:&#34; Hello World&#34;
输出:&#34; olleH dlroW&#34;

答案 12 :(得分:1)

试试这个。它考虑了任何类型的标点符号和空白字符。

public String reverseWordByWord(String inputStr)
{
    BreakIterator wordIterator = BreakIterator.getWordInstance();
    wordIterator.setText(inputStr);
    int start = wordIterator.first();
    StringBuilder tempBuilder;
    StringBuilder outBuilder = new StringBuilder();
    for (int end = wordIterator.next(); end != BreakIterator.DONE; start = end, end = wordIterator.next())
    {
        tempBuilder = new StringBuilder(inputStr.substring(start, end));
        outBuilder.append(tempBuilder.reverse());
    }
    return outBuilder.toString();
}

答案 13 :(得分:1)

我要做的第一件事就是将代码翻转的代码分开,然后单独翻转每个单词。这个内循环:

for(int j = temp.length()-1; j >= 0; j--)
{
    reverse += temp.charAt(j);
    if((j == 0) && (i != strLeng))
        reverse += " ";
}

将是一个函数/方法调用。

另外,为了使代码更高效,而不是使用+运算符连接字符串,我会使用字符串缓冲类。例如StringBufferStringBuilder

答案 14 :(得分:1)

您可以使用StringUtils

return StringUtils.reverseDelimitedString(str, " ");

答案 15 :(得分:1)

如何使用这样的东西?

String string="yourWord";
String reverse = new StringBuffer(string).reverse().toString();

答案 16 :(得分:1)

首先,您应该将它与三个函数分离。第一个使用空格作为分隔符打破字符串列表中的大字符串,第二个反转一个不带空格的字符串,以及最后连接的字符串。

当你这样做时,更容易找到导致空间出现的原因。您已经可以在当前代码中看到,但我不会告诉您:D。

答案 17 :(得分:0)

这是一个不使用字符串功能的解决方案,如reverse,substring,split或tokenizer。我的2美分

Environment.RData

答案 18 :(得分:0)

import java.util.*;
public class REVERSE
{
    public static void main()
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter words: ");
        String word = new String(input.nextLine());
        String reverse[] = word.split(" ");
        String Finalword = " ";
        for(int y = reverse.length-1;y>=0;y--){
            Finalword += reverse[y]+" ";
        }
        System.out.println(Finalword);
    }
}

答案 19 :(得分:0)

这是最简单的方法使用ArraylistTokenizer()逐字翻转字符串这是一个不错的选择...看看它:

import java.util.*;

class ReverseWords{

  public static void main(String args[]){

    Scanner sc = new Scanner(System.in);

    System.out.println(" Please Enter The String \n");
      String st=sc.nextLine();

    //Using ArrayList
      ArrayList<String> List =new ArrayList<String>();
      StringTokenizer tokens=new StringTokenizer(st);

        while(tokens.hasMoreTokens()){
            List.add(tokens.nextToken());
        }
    Collections.reverse(List);

    Iterator itr=List.iterator();  
    while(itr.hasNext()){  
       System.out.print(itr.next()+" ");  
    }  

  }
}

答案 20 :(得分:0)

请尝试它可能对您有帮助

open(my $file, '-|', '/usr/bin/gzip -dc file.gz') or die $!;
...
close $file;
print "File closed\n";
system 'pwd';
print "opening file\n";

open(my $file2, '-|', '/usr/bin/gzip -dc  file.gz') or die "couldn't open file,$!";
print "File opened\n";
close $file2;

答案 21 :(得分:0)

这应该适合你:

import java.io.*;

class internal1 {
    public static void main(String s[] {
        DataInputStream dis = new DataInputStream(System.in);

        try {
            String a = "";
            String b = "";
            System.out.print("Enter the string::");
            a = dis.readLine();
            System.out.print(a.length());
            System.out.println(" ");
            for (int i = 0; i <= a.length() - 1; i++) {
                if (a.charAt(i) == ' ' || a.charAt(i) == '.') {
                    for (int j = b.length() - 1; j >= 0; j--) {
                        System.out.print(b.charAt(j));
                    }
                    b = "";
                    System.out.print(" ");
                }
                b = b + a.charAt(i);
            }
        }
        catch (Exception e) {
        }
    }
}

答案 22 :(得分:0)

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {
    public static void main(String[] args) {
        String str = "Example String Value";
        List<Character> chars = str.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
        chars.add(' ');
        List<String> strs = new ArrayList<>();
        final String[] s = {""};
        chars.forEach(character -> {
            if (character != ' ') {
                s[0] += character.toString();
            } else {
                strs.add(s[0]);
                s[0] = "";
            }
        });
        int size = strs.size();
        while (size > 0) {
            System.out.print(strs.get(size - 1) + " ");
            size--;
        }
    }
}

答案 23 :(得分:0)

public class ReverseWord {

    public static void main(String[] args) {
        String reverseString = "How are you";
        String[] splitt = reverseString.split(" ");
        StringBuffer str= new StringBuffer();
        String revStr;
        for (int i = splitt.length - 1; i >= 0;i--) {
            revStr = splitt[i];
            str.append(revStr.toString()).append(" ");
        }
        System.out.println(str);
    }
}

答案 24 :(得分:0)

/* this code uses while loop and the position of spaces come correctly which is 
  a problem if you use for loop */


import java.util.*;
class StrWordRev
{
public void rev(String s)
    {
        for(int i=s.length()-1;i>=0;i--)
        {
            System.out.print(s.charAt(i));
        }
        System.out.print(" ");
    }

public void main()
{
    Scanner sc=new Scanner(System.in);
    String s,s1="";
    System.out.println("Enter the string : ");
    s=sc.nextLine();
    int i=0;
    while(i<s.length())
    {
        s1="";
        while(i<s.length() && s.charAt(i)!=' ')
        {
            s1=s1+s.charAt(i);
            i++;
        }
        rev(s1);
        i=i+1;
    }
}

答案 25 :(得分:0)

public String reverseEach(String input)
{
    String[] test = input.split(" ");
    String output="";
    for(String t:test)
    {
        String p ="";
        for(int i=t.length()-1;i>=0;i--)
        {
            p=p+t.charAt(i);
        }
        output=output+p+" ";
    }
    return output;
}

答案 26 :(得分:0)

我试着没有分割功能。而是使用substring和for循环。

static String reverseSentenceWithoutSplit(String str){
    StringBuilder sb = new StringBuilder();
    char [] charArray = str.toCharArray();
    int endindex = charArray.length-1;
    // loop in reverse, char by char
    for(int i=charArray.length-1; i>=0; i--){
        char c = charArray[i];
        if(c==' '){
            sb.append(str.substring(i + 1, endindex+1)); // substring- start index inclusive, end index exclusive
            endindex=i-1;// move to first letter
            sb.append(c); // include the space
        }
        if(i==0){ //grab the last word
            sb.append(str.substring(i, endindex+1));
        }
    }
    if(sb.length()==0){ // handle case where string has no space
        return str;
    }
    return sb.toString();
}

输入:在你身后是压迫的象征 输出:压迫符号a是你背后

输入:ThisIsAllOneWord 输出:ThisIsAllOneWord

答案 27 :(得分:0)

这个怎么样:

    public class Main {
    public static void main(String args[]){
        String input ="***NGuyen**Van******A*******";
        String temp = "";
        String result ="";
        for( int i = 0 ; i < input.length() ; i++)
        {
            if(input.charAt(i) != '*')
            {
                temp = temp + input.charAt(i);
            }
            else
            {
                if(!temp.equals(""))
                    result = temp + result;
                result =  input.charAt(i) + result ;
                temp ="";
            }
        }

        System.out.println(result);
    }
}
Output: *******A******Van**NGuyen***

答案 28 :(得分:0)

我认为下面的代码比这里提供的任何代码都更有效:

public static void revWordsInStringCStyle(String str){
    char [] str_ch = str.toCharArray();
    System.out.println(str);
    char temp;
    int len = str_ch.length;
    int left = len-1;

    for(int right =0; right<len/2 ;right++){
        temp = str_ch[left];
        str_ch[left] = str_ch[right];
        str_ch[right] = temp;
        left--;
    }

    for(int i =0; i < len ; i++){
        System.out.print(str_ch[i]);

    }

}

示例:“hello world”

将成为:“dlrow olleho”

答案 29 :(得分:0)

  // Create Scanner object
  Scanner s=new Scanner(System.in);

  // Take no.of strings that the user wants
  int n=s.nextInt();

  // Create a temp array
  String temps[]=new String[n];

  // Initialize the variable before the user input is stored in it
  String st="";

  // Create a words array
  String words[];

  // Skip first line, if not used user input will be skipped one time 
  s.nextLine();

  // Read the no.of strings that user wish to..
  for(int k=0;k<n;k++)
  {

  System.out.println("String #"+(k+1)+": ");

  // Read line
  st=s.nextLine();

 // Split words with a space, because words has spaces at start, end positions.
 words=st.split(" "); 

 // Initialize temps[k] to avoid null
 temps[k]="";

 // Reverse string now!
 for(int i=words.length-1;i>=0;i--)
 {

 // Put each word in user input string from end to start with a space
 temps[k]+=words[i]+" ";

 }
 }

    // Now print the words!
    for(int i=0;i<n;i++)
    {

    // Print the reversed strings, trim them to avoid space at last, see in the reverse logic loop, space is attached at last!
    System.out.println("String #"+(i+1)+": "+temps[i].trim());

    }

答案 30 :(得分:0)

   StringBuilder sb = " This  is cool";
    sb.reverse(); //sb now contains "looc si  sihT "
    System.out.println(sb);
    for(int i = 0; i < sb.length(); i++)
    {
        int index = sb.indexOf(" ", i);
       // System.out.println(index);
        if(index > 0)
        {
            sb.replace(i, index, new StringBuilder(sb.substring(i, index)).reverse().toString());
            i = index;
        }
        if(index < 0)

        {
            sb.replace(i, sb.length(), new StringBuilder(sb.substring(i, sb.length())).reverse().toString());
            break;
        }
    }
    System.out.println(sb);
   //output "cool is  This "

答案 31 :(得分:0)

获取字符串并使用Stack方法和StringTokenizer对象及其方法,我们可以使用delimeter将字符串剪切为单词。通过Stack Natural功能将(push)所有单词插入Satck并从Stack中删除(pop)所有单词。然后打印那些全部。

在这里我们可以采用String s =“hello brave new world”

import java.util.*;
 public class StringReverse {   
  public static void main(String[] argv) { 
      String s = "hello brave new world";      
      Stack<String> myStack = new Stack<String>();
      StringTokenizer st = new StringTokenizer(s); 
        while (st.hasMoreTokens())
           myStack.push((String) st.nextElement());      
           // Print the stack backwards     
           System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");     
         while (!myStack.empty()) {        
           System.out.print(myStack.pop());       
           System.out.print(' ');     
        }     System.out.println('"');
    } 
} 

如果您使用自己的任何包,请检查Output of above program

答案 32 :(得分:0)

所以,我假设你正在学习/练习java,并且家庭作业问题的风险很高......这意味着你要么爱或恨这个答案......

如果你看一下String对象的源代码,你会在里面找到类似的内容:

private final char value[]; //this stores the String's characters

第一步是使用

获取值[]
char[] myChars = str.toCharArray();

注意函数实现(来自openjdk-7),它返回数组的副本而不是原始的副本,因为String对象是不可变的。

public char[] toCharArray() {
    char result[] = new char[count];
    getChars(0, count, result, 0); //Calls System.arraycopy(...)
    return result;
}

现在我们已经myChars我们可以使用它并以线性时间O(n)得到结果!

public static String reverseWordByWord(String str) {
    char[] myChars = str.toCharArray();
    int stringLen = myChars.length;

    int left = 0, right = 0;
    for(int index = 0; index < stringLen; index++) {
        if(chars[index] == ' ') {
            //assign right
            reverse(chars, left, right);
            //update left
        }
    }
    //Don't forget to handle the boundary case (last word in the String)!
}

这是反向功能:

private static void reverse(char[] chars, int left, int right) {
    while(left < right) {
        //Would you know how to swap 2 chars without using a "char tmp" variable? ;)
        //Update left and right
    }
}

现在只是为了好玩,你可能想要尝试获得以下输出,也许你会从一些有朝一日幻想的面试官那里得到这个确切的问题:

world new brave hello

答案 33 :(得分:0)

我自己对Java很陌生,我希望自己被打败了,但我还是觉得我还是试试看。您可以通过构建字符串来解决额外的空白问题,并假设您将在末尾删除不需要的额外空间。如果考虑性能,那么您可能想重新考虑这个!

编辑:请注意,我的解决方案(现在)处理前导和尾随空格。

public class StringReversal {

public static void main(String[] args) {
    String str = "hello brave new world";
    System.out.println("\"" + reverseWordByWord(str) + "\"");
}

public static String reverseWordByWord(String str) {
    String reverse = "";
    boolean first = true;
    for (String s : str.split(" ")) {
        if (first) {
            first = false;
        } else {
            reverse += " ";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; --i) {
            sb.append(s.charAt(i));
        }
        reverse += sb.toString();
    }
    while (reverse.length() < str.length()) {
        reverse += " ";
    }
    return reverse.substring(0, reverse.length());
}
}

答案 34 :(得分:0)

public String reverseStringWordByWord(String input) {
        StringBuilder returnValue = new StringBuilder();
        int insertIndex = 0;
        for(int i = 0;i < input.length();i++ ) {
            if(input.charAt(i)!=' ') {
                returnValue.insert(insertIndex, currentChar);
            } else {
                insertIndex = i+1;
                returnValue.append(currentChar);
            }

        }

        return returnValue.toString();
    }

答案 35 :(得分:0)

以下应该在O(n)中进行,而无需任何昂贵的数组复制或重新构造字符数组长度。处理多个前置,中间和尾随空格。

public class ReverseString {

    public static void main(String[] args) {
        String string1 = "hello brave new world";
        String string2 = "hello brave new world ";
        String string3 = " hello brave new world";
        String string4 = " hello  brave          new world ";

        System.out.println(reverseStringWordByWord(string1));
        System.out.println(reverseStringWordByWord(string2));
        System.out.println(reverseStringWordByWord(string3));
        System.out.println(reverseStringWordByWord(string4));
    }

    private static String reverseStringWordByWord(String string) {
        StringBuilder sb = new StringBuilder();
        int length = string.length();
        for(int i=0;i<length;i++) {
            char c = string.charAt(i);
            if(c == ' ') {
                sb.append(c);
            } else {
                int j = i;
                while(j < length && string.charAt(j) != ' ') {
                    j++;
                }
                sb.append(reverseString(string.substring(i, j)));
                i = j-1;
            }
        }
        return sb.toString();
    }

    private static String reverseString(String string) {
        StringBuilder sb = new StringBuilder();
        for(int i=string.length()-1;i>=0; i--) {
            sb.append(string.charAt(i));
        }
        return sb.toString();
    }

}

答案 36 :(得分:-2)

public class WordReverse {

static StringBuilder sb = new StringBuilder();

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the correct Sentence :");
    String str = sc.nextLine().replaceAll("\\s+", " ");         //remove unwanted space using regex

    int lastIndex = 0, i = 0;

    for (char chars : str.toCharArray()) {
        if (chars != ' ') {
            i++;
        } else {
            myReverse(str.substring(lastIndex, i).toCharArray());
            lastIndex = i + 1;
            i++;
        }
    }
    myReverse(str.substring(lastIndex, i).toCharArray());       //reverse the last word

    System.out.println(sb);
}
public static void myReverse(char c[]) {
    for (int i = (c.length - 1) ; i >= 0 ; i--) {
        sb.append(c[i]);
    }
    sb.append(" ");
} }