[英]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.