反转用户给定字符串的每个单词而不改变其位置

时间:2013-10-19 04:42:20

标签: java string reverse

我需要一些帮助。我发现了一个类似的问题“编写一个Java程序,它将反转用户给定字符串的每个单词而不改变它们的位置并使用任何内置函数。”

我解决了翻译整个句子的代码,但我不知道如何解决这个问题。请帮帮我......

import java.io.*;
class test25 { 
    public static void main(String args[]) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter string: ");
        String s = br.readLine();
        String reverse = "";
        int length = s.length();

        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + s.charAt(i);
        System.out.println("Result:" + reverse); 
    } 
}

26 个答案:

答案 0 :(得分:5)

String str = "hello world";
String revStr = 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;
    }

输入:hello world

输出:olleh dlrow

答案 1 :(得分:5)

1)拆分你的句子(使用split(),这将返回一个数组,比如说单词[])

2)反转数组中的每个单词[]。

3)从数组字[]中重构你的句子。

答案 2 :(得分:2)

这是实现@Maximin的答案的简单代码。

public class Reverse {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        String[] words = input.split(" ");
        String reverse = "";
        for (int i = 0; i < words.length; i++) {
            for (int j = words[i].length() - 1; j >= 0; j--) {
                reverse += words[i].charAt(j);
            }
            System.out.print(reverse + " ");
            reverse = "";
        }
    }
}

通过声明String[] reverse = new String[words.length];,反转的字符串也可以放入它们自己的数组中,允许您根据需要重建句子或格式输出。

答案 3 :(得分:1)

使用空格分割字符串,然后循环遍历String数组的每个元素并将其反转:

public class StringReverse {

public static void main(String args[])
{
String eString=" \"This is the one\"";
String double_quoteString[]=eString.split("\"");
eString=double_quoteString[1];
String[] splitStrings=eString.split("\\s+");
String reverse="";
for(int i=0;i<splitStrings.length;i++)
{
    if(i!=0)
    reverse+=" ";

    for(int j=splitStrings[i].length()-1;j>=0;j--)
    {
        reverse+=splitStrings[i].charAt(j);
    }
}

reverse="\""+reverse+"\"";
System.out.println("reverse is "+reverse);
}

}

答案 4 :(得分:1)

import java.util.*;
class sort
{
public static void main(String[] aaa)
{
String s;
String rev="";
String temp=" ";
Scanner ob=new Scanner(System.in);
System.out.println(" enter String");
s=ob.nextLine();
for(int i=s.length()-1;i>=0;i--)
    rev=rev+s.charAt(i);
System.out.println(rev);
String[] a=rev.split(" ");
int j=a.length-1;
while(j>=0)
{
    temp=temp+a[j];

    temp=temp+" ";
    j--;

}
System.out.println(temp);
}
}

我也尝试了这个。因为我正在学习java,所以我用简单的方法尝试了这段代码。如果我在代码或逻辑方面有任何错误,请纠正我。谢谢....;

答案 5 :(得分:1)

public class ReverseWord {

public static void main(String[] args) {
    String s = "My name is Sarthak ";
    StringBuffer sb = new StringBuffer();
    int n = s.length();
    int j =n;
    int i;
    for(i = n-1;i>=0;i--){

        if(s.charAt(i) == ' '){
            sb.append(s.substring(i+1, j));
            sb.append(" ");
            j = i;
        }
    }
    sb.append(s.substring(0,j));
    System.out.println(sb);
}
}

答案 6 :(得分:0)

public static void main(String[] args) {
    String s;
    s="hi Mister geek is here";//input string 
    int j=0;//for tracking each word
    for(int i=0;i<s.length();i++)//loop for the string 
    {     
        if((int)s.charAt(i)==32/*if has  space checked by ascii code of the space */||i==s.length()-1/* for the end of string */)
        {
            for(int u=i;u>=j;u--)// loop for each word
                System.out.print(s.charAt(u));

            j=i; 
        }
    }  
}

答案 7 :(得分:0)

这很简单,使用内置函数:split & reverse。但是,我的代码对那些想要解决方案而不使用这些功能的人很有帮助。
`导入 java.util.ArrayList; 导入 java.util.Scanner;

class ReverseWordSentence {

public static void main(String[] args) {
    System.out.println("Enter the phrase to be reversed: ");
    Scanner sc = new Scanner(System.in);
    String phrase = sc.nextLine();
    char[] ch = phrase.toCharArray();
    ArrayList<Character> wdl = new ArrayList<Character>();
    for(int i=0; i<ch.length; i++) {
        if(String.valueOf(ch[i]).equals(" ") || (i == phrase.length()-1) ) {
            if (i == phrase.length()-1) {
                wdl.add(ch[i]);
            }
            
            for(int j=wdl.size()-1; j>-1;--j) {
                System.out.print(wdl.get(j));
            }
            
            if(ch[i]==' ') {
                System.out.print(" ");
            }
            
            wdl.clear();
        }
        else
        {
            wdl.add(ch[i]);
        }
    }
}

}`

答案 8 :(得分:0)

package com.practice.stringCodes;

公共类ReverseStringWordsWithoutSplit {

public static void main(String arg[])
{
    String reversedString = "";
    String givenString = "My name is vishal kumar";
    givenString = " " + givenString;
    while(givenString.contains(" "))
    {
    reversedString += (givenString.substring(givenString.lastIndexOf(" "), givenString.length()));
    givenString = givenString.substring(0, givenString.lastIndexOf(" "));
}
    System.out.println(reversedString.trim());
}

}

答案 9 :(得分:0)

package com.learning.misc;

public class WordReversal {

public static void main(String[] args) {

    String str = "functional Interface is core concept of Lambda";

    char arr[] = str.toCharArray();

    int temp = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == ' ' || i == arr.length-1) {
            for (int j = i; j >= temp; j--) {
                System.out.print(arr[j]);
            }
            temp = i+1;
            System.out.print(" ");
        }

    }
}

}

答案 10 :(得分:0)

public class ReverseSent {
    public String Reverse(String s) {
        String s1="",s2="",s3="";
        int l = s.length();
        for(int i=1;i<=l;i++) {
            if(s.charAt(l-i)==' '||(l-i)==0) {
                for(int j=1;j<=s2.length();j++) {
                    s1=s1+s2.charAt(s2.length()-j);
                }
                s3=s3+s1+" ";
                s1="";
                s2="";
            }else if((l-i)==1){
                s2=s2+s.charAt(l-i)+s.charAt(0);
            }else {
                s2=s2+s.charAt(l-i);
            }
        }
        return s3;
    }

    public static void main(String[] args) {
        ReverseSent rs = new ReverseSent();
        String s = "Hello   i am ashish";
        System.out.println(rs.Reverse(s));

    }

}

输入:您好,我是灰烬

输出:我是Ashish

答案 11 :(得分:0)

public class Main {
    public static void main(String[] args) {
        String[] s = new Scanner(System.in).nextLine().split(" ");
        for ( String rs : s) {
            System.out.print(new StringBuilder(rs).reverse()+" ");
        }
    }
}

答案 12 :(得分:0)

public static void main(String[] args) {
    String s = "hello dear";
    String su= "";
    //split the words
    String words [] =s.split(" ");
    //iterate each word and reverse using sb.reverse
    //and append in the string with " "
    for (String w:words) {
        StringBuilder sb = new StringBuilder(w);
        sb.reverse();
        su += sb.toString()+" ";
    }
    System.out.println(su.trim());
    //prints "olleh raed"
}

答案 13 :(得分:0)

public String reverseString(String s) {
    String res = "";
    String reverseFirstPart = "";
    String reverseLastPart = "";

        for (int i=0; i < s.length(); i++){
            if (s.substring(i,i+1).equals(" ") ){
                String firstPart = s.substring(0,i);
                String lastPart = s.substring(i+1,s.length());
                reverseFirstPart = new StringBuilder(firstPart).reverse().toString();
                reverseLastPart = new StringBuilder(lastPart).reverse().toString();
                res = reverseFirstPart + " " + reverseLastPart;
            } else {
                res = s.substring(i,i+1)+res;
                }
    }  return res.substring(reverseLastPart.length());
}

答案 14 :(得分:0)

public class ReverseEachWord {

    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");

        String reverseString = "";

        for (int i = 0; i < words.length; i++) 
        {
            String word = words[i];

            String reverseWord = "";

            for (int j = word.length()-1; j >= 0; j--) 
            {
                reverseWord = reverseWord + word.charAt(j);
            }

            reverseString = reverseString + reverseWord + " ";
        }

        System.out.println(inputString);

        System.out.println(reverseString);

        System.out.println("-------------------------");
    }

    public static void main(String[] args) 
    {

        reverseEachWordOfString("");

        reverseEachWordOfString("");

        reverseEachWordOfString("");

        reverseEachWordOfString("");
    }

}

答案 15 :(得分:0)

此函数将以字符串作为输入并将反转字符串。

public static String reverseWordWise(String input) {

    String[] words = input.split(" ");
    String reversestr = "";

    for(int i = words.length-1; i >= 0; i--){
        if(i == words.length-1){
            reversestr = reversestr + words[i];
        }else{
            reversestr = reversestr + " " + words[i];
        }
    }//end of for loop

    return reversestr;
}

答案 16 :(得分:0)

请完成我的方法。它会为您提供正确的输出: -

public class ReverseWordByword {
    private String sentence="My java virtual world";
    private String newReverse;

    public ReverseWordByword() {
        newReverse="";

    }
    public static void main(String[] args) {
        new ReverseWordByword().wordReverse();
    }
    public void wordReverse(){
        String arr[]=sentence.split("\\ ");

        for(int i=0;i<arr.length;i++){
            newReverse=newReverse+reverseLogic(arr[i])+" ";
        }
        System.out.println(newReverse);
    }
    public String reverseLogic(String word){
        String localWord="";
        char[] charArr=word.toCharArray();
        for(int i=word.length()-1;i>=0;i--){
            localWord=localWord+charArr[i];
        }

        return localWord;
    }
}

答案 17 :(得分:0)

class p3`
//Reverse each word of user given string without altering their position
{
public static String reverseWord(String word)
{
    String r="";
    int len=word.length();
    for(int i=0;i<len;i++)
    {
    r=word.charAt(i)+r; 
    }
    return r;   
}
public static void main(String args[])throws IOException
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter string: ");
        String s = br.readLine()+' ';
        String rev="",s1="";
    int l=s.length();

    for(int i=0;i<l;i++)
    {
        if (s.charAt(i)!=' ')
        {
        rev=rev+s.charAt(i);

        }
        else
        {
        rev=reverseWord(rev);
        s1=s1+rev+" ";
        rev="";
        }   
    }


    System.out.println(s1);
}}

答案 18 :(得分:0)

反向字符串

int switch_prob(int x) 
{
    int result = x;
    switch (x)
    {
        case 50:
        case 52:
            result <<= 2;
            break;
        case 53:
            result >>= 2;
            break;
        case 54:
            result *= 3;
            break;
        default:
            result += 10;   
    }
    return result;
}

输出。伟大的是java

答案 19 :(得分:0)

简单的解决方案: 首先,我们通过扫描仪输入一个字符串 然后我们用空格分开它。 然后我们使用for循环反转它并输出它。

    let appDel  = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext!

    var fetchError : NSError?

    let fetchPredicate = NSPredicate(format: "email == %@", "dog@gmail.com")

    let fetchUsers                      = NSFetchRequest(entityName: "User")
    fetchUsers.predicate                = fetchPredicate
    fetchUsers.returnsObjectsAsFaults   = false


    let fetchedUsers = context.executeFetchRequest(fetchUsers, error: &fetchError) as! [NSManagedObject]

    for fetchedUser in fetchedUsers {

        var deleteUserError: NSError?

        context.deleteObject(fetchedUser)
        context.save(&deleteUserError)
    }

答案 20 :(得分:0)

A different solution and a simple one

public class strrev {
    public static void main(String[] args)throws IOException {
        // TODO Auto-generated method stub
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the string to be reversed");
        String str=br.readLine();
        char rev;
        int k=0;        
        for(int i=0;i<str.length();i++)
        {           
            if(str.charAt(i)==32 ||i==str.length()-1)
            {
                for(int j=i;j>=k;j--)
                {
                    rev=str.charAt(j);
                    System.out.print(rev);
                }
                k=i;
                continue;
            }             
        }
    }
}

答案 21 :(得分:0)

这是一个解决方案

fucntion String reverseSentence(String sentence){
String Rword = "";
String newSentence = "";
char space = ' ';
String empty = "";

if(sentence == null || sentence == empty)
return null; // this could be an error message
else{
      int tempi = 0;
         if(sentence.charAt(0) == space){ 
              Rword = Rword+sentence.charAt(0); // check for when the first char is a space
              tempi++;
         }
        for(int i=tempi; i< sentence.length(); i++){
             if(sentence.charAt(i) == space) //if it reaches a space its a word
             {
                Rword = Rword+sentence.charAt(i);  //add the current space
                newSentence = newSentence+Rword ; //give the reversed word to the new sentence
                Rword = ""; // then empty the word
             }else{
                    Rword = sentence.charAt(i)+Rword ; //while its not a space, reverse.  
                  }
        }
          newSentence = newSentence+Rword; // the last char might not be a space to so the first 
                                           //  if statement in the loop will never happen again, 
                                             //i add the last word after the loop
          return newSentence;
    }
}

答案 22 :(得分:0)

我也面临一个类似的问题,但没有明确这一轮,因为我的方法对于评估我的答案的人来说过于复杂,我在这里分享,希望它有所帮助。

package interviewPractice;
import java.util.Scanner;

public class SentenceToWord 
{
    public static int getNumberOfWords(String sentence)
    {
        int counter=0;
        for(int i=0;i<sentence.length();i++)
        {
            if(sentence.charAt(i)==' ')
            counter++;
        }
        return counter+1;
    }

    public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring() 
    {
        int counter=0;
        char charArrayToReturn[]=new char[end-start];
        for(int i=start;i<end;i++)
        {
            charArrayToReturn[counter++]=sentence.charAt(i);
        }
        return charArrayToReturn;
    }

    public static char[][] getWordsFromString(String sentence)
    {
        int wordsCounter=0;
        int spaceIndex=0;
        int length=sentence.length();
        char wordsArray[][]=new char[getNumberOfWords(sentence)][]; 
        for(int i=0;i<length;i++)
        {
            if(sentence.charAt(i)==' ' || i+1==length)
            {
            wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
            spaceIndex=i+1; //increment space index
            }
        }
        return  wordsArray; //return the 2 dimensional char array
    }


    public static void main(String[] args) 
    {
    System.out.println("Please enter the String");
    Scanner input=new Scanner(System.in);
    String userInput=input.nextLine().trim();
    int numOfWords=getNumberOfWords(userInput);
    char words[][]=new char[numOfWords+1][];
    words=getWordsFromString(userInput);
    System.out.println("Total number of words found in the String is "+(numOfWords));
    for(int i=0;i<numOfWords;i++)
    {
        System.out.println(" ");
        for(int j=0;j<words[i].length;j++)
        {
        System.out.print(words[i][j]);//print out each char one by one
        }
    }
    }

}

现在你将你的单词存储在数组“单词”中,然后反转它们。

答案 23 :(得分:0)

非常简单的代码在这里

class reverse{
    public static StringBuilder sb;    
    public static void main(String args[])
    {        
       String str[] = "He is the one".split(" ");        
       String finalStr="";            
       for(int i = str.length-1; i>= 0 ;i--)    
       {                
            finalStr += str[i]+" ";
            finalStr.toString();

            sb=new StringBuilder(finalStr);
            sb.reverse();              
      }         
       System.out.print(sb);
    }
}

答案 24 :(得分:0)

课程计划     {         static void Main(string [] args)         {             int i = 0,j = 0;             string test =“你好先生,我很好”;             StringBuilder sb = new StringBuilder();             char [] str = test.ToCharArray();             char [] revstr;             而(i&lt; str.Length)                 我++;                 一世 - ;             for(int k = i; k&gt; = j;)             {

            if (str[k] == ' ')
            {
                for (int l = k; l < i; l++)
                {   

                    sb.Append(str[l+1]);

                }
                sb.Append(" ");
                i = k - 1;  
            }
            k--;

        }
        for (j = 0; j <= i; j++)
            sb.Append(str[j]);
        Console.WriteLine(sb);

        Console.ReadLine();

答案 25 :(得分:0)

这是一个解决方案:

public static String reverseEach(String inputString) {
  String[] parts = inputString.split(" ");
  StringBuilder sb = new StringBuilder();
  for (String p : parts) {
    sb.append(new StringBuffer(p).reverse().toString());
    sb.append(' ');
   }
   return sb.toString();
}