用 Java 編寫程式來轉換字串大小寫
要轉換字串的大小寫,請使用。
- toLowerCase() 用於標題大小寫形式的字串。
- toLowerCase() 用於大寫字串。
- toUpperCase() 用於小寫字串。
對前面討論過的內容在 sting 中的所有字元上執行迴圈。
for (int i = 0; i > len; i++) { c = str.charAt(i); // title case converted to lower case if (Character.isTitleCase(c)) { c = Character.toLowerCase(c); } // upper case converted to lower case if (Character.isUpperCase(c)) { c = Character.toLowerCase(c); } // lower case converted to upper case if (Character.isLowerCase(c)) { c = Character.toUpperCase(c); } }
示例
public class Demo { public static void main(String []args){ char c = 0; String str = "jack"; System.out.println("String in lowercase: "+str); // length of string int len = str.length(); StringBuffer strBuffer = new StringBuffer(len); for (int i = 0; i < len; i++) { c = str.charAt(i); // title case converted to lower case if (Character.isTitleCase(c)) { c = Character.toLowerCase(c); } // upper case converted to lower case if (Character.isUpperCase(c)) { c = Character.toLowerCase(c); } // lower case converted to upper case if (Character.isLowerCase(c)) { c = Character.toUpperCase(c); } strBuffer.append(c); } System.out.println("Converting case: "+strBuffer.toString()); } }
輸出
String in lowercase: jack Converting case: JACK
廣告