你的位置:首页 > Java教程

[Java教程]java字符串大小写字母互改


import java.util.Scanner;public class Test {  /**   * 测试数据   *   * @param args   */  public static void main(String[] args) {    Scanner sc = new Scanner(System.in);    String s = sc.nextLine();    System.out.println(ExchangeStringA(s));    System.out.println(ExchangeStringB(s));  }  /**   * 方式一   *   * @param s   * @return   */  public static String ExchangeStringA(String s) {    StringBuffer result = new StringBuffer();    String lowerString = s.toLowerCase();  //这两步    String upString = s.toUpperCase();    //是关键    for (int i = 0; i < s.length(); i++) {      if (s.charAt(i) == lowerString.charAt(i)) {        result.append(upString.charAt(i));      } else {        result.append(lowerString.charAt(i));      }    }    return result.toString();  }  /**   * 方式二 以字母的ascii码来操作 大小写之间相差32   * a-z:97-122   * A-Z:65-90   * @param s   * @return   */  public static String ExchangeStringB(String s) {    char c[] = s.toCharArray();    for (int i = 0; i < c.length; i++) {      if (c[i] >= 65 && c[i] <= 90) {        c[i] = (char) (c[i] + 32);      } else {        c[i] = (char) (c[i] - 32);      }    }    return String.valueOf(c);  }}