java 反转句子中每个单词中的字符 - 代码日志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11544966/
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
Reversing characters in each word in a sentence - Stack Implementation
提问by amiregelz
This code is inside the main
function:
这段代码在main
函数内部:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty()
function:
这是empty()
功能:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence
I am getting this output: lpmaxe
. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
它不能正常工作,因为通过键入example sentence
我得到了这个输出:lpmaxe
。第一个字母丢失,循环停止,而不是越过空格数到句子的下一部分。
I am trying to achieve this:
我正在努力实现这一目标:
This is a sentence
---> sihT si a ecnetnes
This is a sentence
---> sihT si a ecnetnes
回答by Roddy of the Frozen Peas
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
根据对原始帖子的修改,OP 现在表示他的目标是颠倒句子中单词的字母顺序,但将单词保留在初始位置。
The simplest way to do this, I think, is to make use of the String split
function, iterate through the words, and reverse their orders.
我认为,最简单的方法是使用 Stringsplit
函数,遍历单词并颠倒它们的顺序。
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord
is defined as:
其中方法reverseWord
定义为:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty
method has been changed to:
并且empty
方法已更改为:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
原始回复
The original question indicated that the OP wanted to completely reverse the sentence.
最初的问题表明 OP 想要完全颠倒句子。
You've got a double-looping construct where you don't really need it.
你有一个双循环结构,你并不真正需要它。
Consider this logic:
考虑这个逻辑:
- Read each character from the input string and push that character to the stack
- When the input string is empty, pop each character from the stack and print it to screen.
- 从输入字符串中读取每个字符并将该字符压入堆栈
- 当输入字符串为空时,从堆栈中弹出每个字符并将其打印到屏幕上。
So:
所以:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
回答by darrenp
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence
you want it to output elpmaxe ecnetnes
notecnetnes elpmaxe
.
我假设您希望代码执行的是依次反转每个单词,而不是整个字符串。因此,鉴于example sentence
您希望它输出的输入elpmaxe ecnetnes
notecnetnes elpmaxe
。
The reason that you see lpmaxe
instead of elpmaxe
is because your inner while
-loop doesn't process the last character of the string since you have i < sentence.length() - 1
instead of i < sentence.length()
. The reason that you only see a single word is because your sentence
variable consists only of the first tokenof the input. This is what the method Scanner.next()
does; it reads the next (by default) space-delimited token.
您看到lpmaxe
而不是的原因elpmaxe
是因为您的内部while
循环不处理字符串的最后一个字符,因为您有i < sentence.length() - 1
而不是i < sentence.length()
. 您只看到一个单词的原因是您的sentence
变量仅包含输入的第一个标记。这就是该方法的Scanner.next()
作用;它读取下一个(默认情况下)以空格分隔的标记。
If you want to input a whole sentence, wrap up System.in
as follows:
如果你想输入一个完整的句子,总结System.in
如下:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine()
.
并调用reader.readLine()
。
Hope this helps.
希望这可以帮助。
回答by Dennis Meng
Assuming you've already got your input in sentence
and the Stack object is called stk
, here's an idea:
假设您已经输入sentence
并调用了 Stack 对象stk
,这里有一个想法:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') {
to something like if (c == ' ' || c == '.' || c == ',') {
and so on.)
因此,它将一次扫描一个字符。如果我们碰到一个空格字符,我们会假设我们已经到了一个单词的末尾,反向吐出那个单词,打印那个空格字符,然后继续。否则,我们会将字符添加到堆栈中并继续构建当前单词。(如果您还想允许使用句点、逗号等标点符号,请更改if (c == ' ') {
为类似的if (c == ' ' || c == '.' || c == ',') {
内容。)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
至于为什么你只得到一个词,darrenp已经指出了。(就我个人而言,除非速度有问题,否则我会使用 Scanner 而不是 BufferedReader,但这只是我的意见。)
回答by Mark Salvino
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
}
回答by Hari Krishna
public class ReverseofeachWordinaSentance {
公共类 ReverseofeachWordinaSentance {
/**
* @param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
}
回答by cow12331
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
}
This can pass in leetcode
这个可以传入leetcode