Java 反转用户给定字符串的每个单词而不改变它们的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19462439/
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
Reverse each word of user given string without altering their position
提问by debanjan
I need a little help. I found a question like "Write a Java program that will reverse each word of user given string without altering their position and using any built in function."
我需要一点帮助。我发现了一个问题,比如“编写一个 Java 程序,该程序将反转用户给定字符串的每个单词,而不改变它们的位置并使用任何内置函数。”
I solved a code for reversing the whole sentence, but I don't know how to solve this one. Please help me...
我解决了一个用于反转整个句子的代码,但我不知道如何解决这个问题。请帮我...
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);
}
}
回答by Maximin
1) Split your sentence (using split(), this will return an array, say words[])
1)拆分你的句子(使用split(),这将返回一个数组,比如words[])
2) Reverse each word in the array words[].
2) 反转数组 words[] 中的每个单词。
3) Reconstruct your sentence from the array words[].
3) 从数组 words[] 重建你的句子。
回答by Jose Cifuentes
Here's one solution:
这是一种解决方案:
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();
}
回答by Umang Mehta
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;
}
Input: hello world
输入:你好世界
Output: olleh dlrow
输出:olleh dlrow
回答by x4nd3r
Here is simple code that implements @Maximin's answer.
这是实现@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 = "";
}
}
}
The reversed strings could also be placed into their own array by declaring String[] reverse = new String[words.length];
, allowing you the option to reconstruct the sentence or format output as desired.
也可以通过声明将反转的字符串放入它们自己的数组中String[] reverse = new String[words.length];
,让您可以选择根据需要重建句子或格式输出。
回答by user3742204
class Program { static void Main(string[] args) { int i = 0,j=0; string test = "Hello Sir I am good"; StringBuilder sb = new StringBuilder(); char[] str = test.ToCharArray(); char[] revstr; while (i < str.Length) i++; i--; for (int k = i; k >= j;) {
class Program { static void Main(string[] args) { int i = 0,j=0; string test = "你好先生,我很好"; StringBuilder sb = new StringBuilder(); char[] str = test.ToCharArray(); 字符[] revstr; while (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();
回答by user3369245
very simple code is here
非常简单的代码在这里
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);
}
}
回答by Sujal Mandal
i also faced a similar question but didn't clear the round because my approach was too complex for the person evaluating my answer, i am sharing it here, hope it helps someone.
我也遇到了类似的问题,但没有明确这一轮,因为我的方法对于评估我的答案的人来说太复杂了,我在这里分享,希望对某人有所帮助。
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
}
}
}
}
Now you have your words stored in the array "words" just reverse them.
现在您将单词存储在数组“单词”中,只需将它们反转即可。
回答by Uche Dim
here is one solution
这是一种解决方案
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;
}
}
回答by Meht4409
split the string using space and then loop through each element of String array and reverse it:
使用空格分割字符串,然后循环遍历 String 数组的每个元素并将其反转:
public class StringReverse {
公共类 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);
}
}
}
回答by amjeremiad
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);
}
}
I too tried this.Since I am learning java i tried this code in simple way.If i did any mistake in code or logic please correct me.Thank you....;
我也试过这个。自从我学习java以来,我以简单的方式尝试了这段代码。如果我在代码或逻辑上犯了任何错误,请纠正我。谢谢....;