-2

我需要一点帮助。我发现了一个问题,例如“编写一个 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); 
    } 
}
4

26 回答 26

5

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

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

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

于 2013-10-19T04:46:50.923 回答
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;
    }

输入:你好世界

输出:olleh dlrow

于 2013-10-19T04:53:24.250 回答
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];,从而允许您根据需要重新构建句子或格式输出。

于 2013-10-19T05:58:34.617 回答
1

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

公共类 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);
}

}

于 2015-05-05T13:59:02.673 回答
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,所以我以简单的方式尝试了这段代码。如果我在代码或逻辑上犯了任何错误,请纠正我。谢谢....;

于 2015-07-18T06:29:33.087 回答
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);
}
}
于 2017-06-24T06:42:03.173 回答
0

类程序 { 静态无效 Main(string[] args) { int i = 0,j=0; string test = "你好,先生,我很好"; StringBuilder sb = new StringBuilder(); char[] str = test.ToCharArray(); 字符[] revstr; 而 (i < str.Length) i++; 一世 - ; for (int k = i; k >= 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();
于 2014-06-15T12:12:35.007 回答
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();
}
于 2013-10-19T04:49:07.063 回答
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;
    }
}
于 2014-09-10T18:06:11.363 回答
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);
    }
}
于 2014-08-12T08:17:45.667 回答
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
        }
    }
    }

}

现在您将单词存储在数组“单词”中,只需将它们反转即可。

于 2014-08-24T20:45:05.230 回答
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

输出:ashish am i Hello

于 2018-08-08T17:21:24.463 回答
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; 
        }
    }  
}
于 2016-01-07T19:18:54.740 回答
0

使用内置功能非常简单:拆分和反转。但是,我的代码对于那些想要解决方案而不使用这些功能的人很有帮助。
`导入java.util.ArrayList;导入 java.util.Scanner;

类 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]);
        }
    }
}

}`

于 2021-08-02T17:05:57.120 回答
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());
}
于 2017-12-11T22:03:24.180 回答
0

反转字符串

     import java.util.*;

     public class Main
   {
        public static void main(String[] args)
     {
         String m="java is           great";
          String temp="";
          System.out.println(m);
          String store="";
           int cnt=0;
       char [] p=m.toCharArray();
      for(int i=p.length-1;i>=0;i--)
       {
       if(p[i]==' '||i==0)
            {
        if(cnt>=1||i==0)
        {
            if(i==0)
                temp=temp+p[i];
            store=store+new StringBuilder(temp).reverse().toString();
            temp="";
            cnt=0;
        }
        if(p[i]==' ')
        {
          store=store+p[i];
        }


    }
    else
    {
        temp=temp+p[i];
        System.out.println(p[i]);
        cnt++;
    }
       }
     System.out.println(store);
   }
 }

输出。伟大的是java

于 2015-10-19T05:41:14.730 回答
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;
}
于 2017-07-01T07:23:19.503 回答
0

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

     public class reverse{

             public static void main(String[] args){

                 Scanner sc = new Scanner(System.in);

                 System.out.println("enter string");

                    String s = sc.nextLine();

                    String [] words = s.split(" "); // space for words

                    for(int i = words.length - 1; i >= 0; i--)
                 {

                    System.out.print(words[i] + " ");

                 }
            }
}
于 2015-08-06T15:18:34.920 回答
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;
    }
}
于 2017-03-21T09:01:10.767 回答
0

不同的解决方案和简单的解决方案

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;
            }             
        }
    }
}
于 2015-07-31T19:31:33.560 回答
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()+" ");
        }
    }
}
于 2018-03-11T17:44:01.803 回答
0

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

}

于 2019-10-18T16:41:42.340 回答
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);
}}
于 2016-01-11T06:43:54.083 回答
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"
}
于 2018-01-03T17:50:09.270 回答
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("");
    }

}
于 2017-07-29T10:38:43.503 回答
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(" ");
        }

    }
}

}
于 2019-10-09T11:22:01.413 回答