-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
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 に答える
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

スペースを使用して文字列を分割し、文字列配列の各要素をループして逆にします。

パブリック クラス 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
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

私も同様の質問に直面しましたが、回答を評価する人にとって私のアプローチが複雑すぎたため、ラウンドをクリアしませんでした。ここで共有しています。誰かの役に立てば幸いです。

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
        }
    }
    }

}

これで、単語を配列 "words" に格納して、それらを逆にするだけです。

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

ここに1つの解決策があります

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

別の解決策と単純な解決策

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 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 am i Hello

于 2018-08-08T17:21:24.463 に答える
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 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

逆文字列

     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

パッケージcom.practice.stringCodes;

public class 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 に答える