寫一個 Java 程式,反轉字串中的每個單詞並進行切換?
若要執行反向切換,請拆分字串中的單詞,使用 split() 方法反轉每個單詞,將每個單詞的首字母改為小寫,而其餘字母改為大寫。
示例
import java.lang.StringBuffer; public class ToggleReverse { public static void main(String args[]){ String sample = "Hello How are you"; String[] words = sample.split(" "); String result = ""; for(String word:words){ StringBuffer s = new StringBuffer(word); word = s.reverse().toString(); String firstSub = word.substring(0, 1); String secondSub = word.substring(1); result = result+firstSub.toLowerCase()+secondSub.toUpperCase()+" "; } System.out.println(result); } }
輸出
oLLEH wOH eRA uOY
廣告