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');
    }
}

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Ramer42/article/details/83388062