1. 程式人生 > >Java的字串操作練習

Java的字串操作練習

 完成一個java application應用程式,完成字串的各種操作。

public class s221 {
    public static void main(String[] args){
        String a = "adcsdadcbcbcs";
        String b = "def";

        //字串相加
        String c = a + b;
        System.out.println(c);

        //判斷字串相等
        if(a.equals(b) == true){
            System.
out.println("兩個字串相等"); } else{ System.out.println("兩個字串不相等"); } //查詢某一子字串是否被包含在此字串之中,如果包含,包含了多少次 String com = "adc"; //定義需要查詢的子字串 char[] ch1 = com.toCharArray(); char[] ch = a.toCharArray(); //a為需要被查詢目標字串 int n = ch.length; int
m = ch1.length; int i = 0; int x; int nn = 0; while(i<=n-m){ if(ch[i]==ch1[0]){ x = 1; while(x<m && ch[i+x]==ch1[x]){ x++; } if(x==m){ nn++;
} i=i+x; }else { i++; } } if(nn==0){ System.out.println("此字串中沒有包含該子字串"); }else{ System.out.println("此字串中包含該子字串" + nn + "次"); } //操作包括已知一個字串及其包含的某一子字串,把此子字串替換為其他的新的指定字串 String s = "my.test.txt"; String s1 = s.replace(".", "#"); //把字串中的"."替換為"#" System.out.println(s1); //格式化輸出 System.out.printf("字母a的大寫是:%c %n", 'A'); } }

輸出結果:
在這裡插入圖片描述