繁体   English   中英

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

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

关于使用StringBuffer而不使用String.split的反向单词。
例如反向
你好,世界
输出必须

    olleh dlrow

    dlrow olleh

任何想法使这个程序?

导入库并使用此功能。

import org.apache.commons.lang.StringUtils;

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

这听起来像是一个作业问题,所以与其给您实际的代码,不如告诉我使用伪代码的初衷。

假设:您只需要使用一个StringBuffer就位。 单词之间用空格隔开。 除StringBuffer外,不能使用其他任何东西。

您将需要编写一个称为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;

注意:这只是解决问题的多种方法之一。

这是一种进行方法:

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

这是代码中的样子

已删除,因为这是家庭作业;-)

输入:

"   HeLlo   world   "

输出:

'   olLeH   dlrow   '

暂无
暂无

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

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