1. 程式人生 > >Java字串處理

Java字串處理

程式碼:

 1 import java.util.Scanner;
 2   
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scanner =new Scanner(System.in);
 6         String string;
 7         while(scanner.hasNext()) {
 8             String res="";
 9             string=scanner.next();//
使用next()方法,則每次取一串字元,使用nextLine()則每次可取一行字元,包括空格等分隔符 10 for(int i=0;i<string.length();i++) { 11 char c=string.charAt(i); 12 if(c>='A'&&c<='Z') { 13 c=(char) (c+32); 14 if(c=='z') 15 c='a';
16 else 17 c++; 18 res+=c; 19 }else if(c>='a'&&c<='z'){ 20 //int indexOf(ch)方法,返回指定字元在此字串中第一次出現處的索引 21 if ("abc".indexOf(c) > -1) { 22 res += "2";
23 } else if ("def".indexOf(c) > -1) { 24 res += "3"; 25 } else if ("ghi".indexOf(c) > -1) { 26 res += "4"; 27 } else if ("jkl".indexOf(c) > -1) { 28 res += "5"; 29 } else if ("mno".indexOf(c) > -1) { 30 res += "6"; 31 } else if ("pqrs".indexOf(c) > -1) { 32 res += "7"; 33 } else if ("tuv".indexOf(c) > -1) { 34 res += "8"; 35 } else if ("wxyz".indexOf(c) > -1) { 36 res+= "9"; 37 } 38 }else if("0123456789".indexOf(c)>-1) { 39 res+=c; 40 } 41 } 42 System.out.println(res); 43 } 44 } 45 }