简体   繁体   English

java:使用StringBuffer而不使用String.split的反词

[英]java: reverse word using StringBuffer without using String.split

About reverse word using StringBuffer without using String.split. 关于使用StringBuffer而不使用String.split的反向单词。
For example reverse 例如反向
Hello world 你好,世界
The output must 输出必须

    olleh dlrow

not

    dlrow olleh

any idea to make this program?? 任何想法使这个程序?

Import the library and use this function. 导入库并使用此功能。

import org.apache.commons.lang.StringUtils;

String reverseWords(String string) {
    return StringUtils.reverseDelimited(StringUtils.reverse(string), ' ');
}

This sounds like a homework question, so instead of giving you actual code I will tell you what I have in mind using pseudocode. 这听起来像是一个作业问题,所以与其给您实际的代码,不如告诉我使用伪代码的初衷。

Assumption: You have to do it in place using one StringBuffer only. 假设:您只需要使用一个StringBuffer就位。 Words are separated by space. 单词之间用空格隔开。 You cannot use anything other than StringBuffer. 除StringBuffer外,不能使用其他任何东西。

You will need to write a method called reverse 您将需要编写一个称为reverse的方法

/**
 * This method reverse the word starting at startIndex 
 * and of length wordLength. For example:
 * StringBuffer buf = new StringBuffer("hello world");
 * reverse(buf, 0, 5);
 * will result in buf being "olleh world"
 */
reverse(StringBuffer s, int startIndex, int wordLength)

/* Now the pseudo code */
Given StringBuffer sb;
Find all the indexes of all the spaces in sb;
Using the indexes found to calculate the startIndex of each word and the lengths of the word;
call reverse for each of the calculated indexes and lengths;

Note: This is only one of the many ways to solve your problem. 注意:这只是解决问题的多种方法之一。

Here is one way to proceed: 这是一种进行方法:

User a result buffer to store the final string reversed word by word
Use a temp buffer to store each word you fond in the original string

Iterate over the chars in your buffer.
    // Identify a word: a word is terminated when you find a space
    If the actual char is not space then save it to temp buffer
    If the actual char is a space then you have a word witch is stored in temp buffer
        reverse that temp buffer and add it to the result buffer
        add a space the the result buffer
        clear the temp buffer so you can save the next word in it

Here is how it looks like in code 这是代码中的样子

Removed since this is homework ;-) 已删除,因为这是家庭作业;-)

Input: 输入:

"   HeLlo   world   "

Output: 输出:

'   olLeH   dlrow   '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM