java:使用StringBuffer反向使用String而不使用String.split

时间:2012-04-18 08:59:51

标签: java

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

    olleh dlrow

不是

    dlrow olleh

制作这个节目的想法吗?

3 个答案:

答案 0 :(得分:0)

导入库并使用此功能。

import org.apache.commons.lang.StringUtils;

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

答案 1 :(得分:0)

这听起来像是一个家庭作业问题,所以我不会给你实际的代码,而是会告诉你我使用伪代码的想法。

假设:您必须仅使用一个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;

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

答案 2 :(得分:0)

以下是一种方法:

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   '
相关问题