2019-05-21 Java学习日记之String类型Demo

String类的构造方法:

public String():空构造

public String(byte[ ] bytes):把字节数组转成字符串

public String(byte[ ] bytes,int index,int length):把字节数组的一部分转成字符串

public String(char[ ] value):把字符数组转成字符串

public String(char[ ] value,int index,int count):把字符数组的一部分转成字符串

public String(String original):把字符串常量值转成字符串

package com.test;

public class Demo {

    public static void main(String[] args) {
        String s1 =  new String();
        System.out.println(s1);
        
        byte[] arr1 = {97,98,99};
        String s2 = new String(arr1);    //解码,将计算机读的懂的转换成我们读得懂的
 System.out.println(s2); byte[] arr2 = {97,98,99,100,101,102}; String s3 = new String(arr2, 2, 3);//将arr2字节数组从2索引开始转换3个  System.out.println(s3); char[] arr3 = {'a','b','c','d','e'};//将字符数组转换成字符串 String s4 = new String(arr3); System.out.println(s4); String s5 = new String(arr3, 1, 3);//将arr3字符数组,从1索引开始转换3个  System.out.println(s5); String s6 = new String("hello"); System.out.println(s6); } }

String类的常见面试题:

1、判断定义为String类型的s1和s2是否相等

String s1 = “abc”;

String s2 = “abc”;

System.out.println(s1 == s2);

System.out.println(s1.equals(s2));

2、下面这句话在内存中创建了几个对象?

String s1 = new String(“abc”);

3、判断定义为String类型的s1和s2是否相等

String s1 = new String(“abc”);

String s2 = “abc”;

System.out.println(s1 == s2);

System.out.println(s1.equals(s2));

4、判断定义为String类型的s1和s2是否相等

String s1 = “a” + “b” + “c”;

String s2 = “abc”;

System.out.println(s1 == s2);

System.out.println(s1.equals(s2));

5、判断定义为String类型的s1和s2是否相等

String s1 = “ab”;

String s2 = “abc”;

String s3 = s1 +“c”;

System.out.println(s3 == s2);

System.out.println(s3.equals(s2));

    private static void demo1() {
        String s1 = "abc";
        String s2 = "abc";
        System.out.println(s1 == s2);         //true            
        System.out.println(s1.equals(s2));    //true
    }

    private static void demo2() {
        //创建几个对象
        //创建两个对象,一个在常量池中,一个在堆内存中
        String s1 = new String("abc"); System.out.println(s1); } private static void demo3() { String s1 = new String("abc"); String s2 = "abc"; System.out.println(s1 == s2); //false System.out.println(s1.equals(s2)); //true  } private static void demo4() { //byte b = 3 + 4; //在编译时就变成7,把7赋值给b,常量优化机制 String s1 = "a" + "b" + "c"; String s2 = "abc"; System.out.println(s1 == s2); //true System.out.println(s1.equals(s2)); //true  } private static void demo5() { String s1 = "ab"; String s2 = "abc"; String s3 = s1 + "c"; System.out.println(s3 == s2); //false System.out.println(s3.equals(s2)); //true }

String类的判断功能:

boolean equals(Object obj):比较字符串的内容是否相等,区分大小写

boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写

boolean contains(String str):判断大字符串中是否包含小字符串

boolean startWith(String str):判断字符串是否以某个指定的字符串开头

boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾

boolean isEmpty():判断祖符串是否为空

    private static void demo1() {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "Hello";
        
        System.out.println(s1.equals(s2));    //true
        System.out.println(s2.equals(s3));    //false
        
        System.out.println(s1.equalsIgnoreCase(s2));    //true
        System.out.println(s1.equalsIgnoreCase(s3));    //true 不区分大小写
 } private static void demo2() { String s1 = "我爱学习,哈哈"; String s2 = "学习"; String s3 = "xuexi"; String s4 = "我爱"; String s5 = "哈哈"; System.out.println(s1.contains(s2)); //true 判断是否包含传入的字符串 System.out.println(s1.contains(s3)); //false  System.out.println(s1.startsWith(s4)); //true 判断是否以传入的字符串开头 System.out.println(s1.startsWith(s5)); //false  System.out.println(s1.endsWith(s4)); //false 判断是否与传入的字符串结尾 System.out.println(s1.endsWith(s5)); //true  } private static void demo3() { String s1 = "hello"; String s2 = ""; String s3 = null; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); System.out.println(s3.isEmpty()); //java.lang.NullPointerException
  }

""和null的区别:

""是字符串常量,同时也是一个String类的对象,既然是对象当然可以调用String类中的方法

null是空常量,不能调用任何的方法否则会出现空指针异常,null常量可以给任意的引用数据类型赋值

模拟用户登录:

需求:模拟登录,给三次机会,并提示还有几次。

用户名和密码都是admin

Demo:

package com.test;

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); // 创建键盘录入对象
for (int i = 0; i < 3; i++) { System.out.println("请输入用户名:"); String username = sc.nextLine(); // 将键盘录入的用户名存储在username中 System.out.println("请输入密码:"); String password = sc.nextLine(); // 将键盘录入的密码存储在password中
// 如果是字符串常量和字符串变量比较,通常都是字符串常量调用方法,将变量当作参数传递,防止空指针异常 if ("admin".equals(username) && "admin".equals(password)) { System.out.println("欢迎" + username + "登录"); break; } else { if (i == 2) { System.out.println("請明天再來!"); } else { System.out.println("用户名和密码错误!你還有" + (2 - i) + "次機會!"); } } } } }

String类的获取功能:

int length():获取字符串长度

char charAt(int index):获取指定索引位置的字符

int indexOf(int ch):返回指定字符在此字符串中第一次出现处索引

int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引

int indexOf(int ch,int fromIndex):返回指定字符串在此字符中从指定位置后第一次出现处的索引

int indexOf(String str,int fromIndex):返回指定字符串在此字符中从指定位置后第一次出现处的索引

lastIndexOf

String substring(int start):从指定位置开始截取字符串,默认到末尾

String substring(int start,int end):从指定位置开始到指定位置结束截取字符串

    private static void demo5() {
        String s1 = "woaixuexi";
        s1.substring(4);        //subString会产生一个新的字符串,需要将新的字符串记录
        System.out.println(s1);
    }
    private static void demo4() {
        String s1 = "hellokugou";
        String s2 = s1.substring(5);
        System.out.println(s2);
        
        String s3 = s1.substring(0,5);//包含头,不包含尾,左闭右开
        System.out.println(s3);
    }
    private static void demo3() {
        String s1 = "woaixuexi";
        int index = s1.indexOf('i',4);    //从指定位置开始向后找
        System.out.println(index);
        
        int index2 = s1.lastIndexOf("i");//从后向前找,第一次出现的字符
        System.out.println(index2);
        
        int index3 = s1.lastIndexOf('i',7);//从指定位置向前找
        System.out.println(index3);
    }
    private static void demo2() {
        String s1 = "hello";
        int index = s1.indexOf('e');    //参数接收的是int类型的,传递char类型的会自动提升
        System.out.println(index);
        
        int index2 = s1.indexOf('a');    //如果不存在则返回-1
        System.out.println(index2);
        
        int index3 = s1.indexOf("el");    //获取字符串中第一个字符出现的位置
        System.out.println(index3);
        
        int index4 = s1.indexOf("eo");
        System.out.println(index4);
    }
    private static void demo1() {
        //int[] arr = {11,22,33};
        //System.out.println(arr.length);        //数组中的length是属性
        
        String s1 = "hello";
        System.out.println(s1.length());    //length()是一个方法        
        
        String s2 = "我愛學習,造嗎?";
        System.out.println(s2.length());    
        
        char c = s2.charAt(5);    //根据索引获取对应位置的字符
        System.out.println(c);
        char c2 = s2.charAt(10);//StringIndexOutOfBoundsException字符串索引越界异常
        System.out.println(c2);
    }

遍历数组:

private static void demo() {
        String s = "hello";
        
        for (int i = 0; i < s.length(); i++) {    //通过for循环获取到字符串中的每个字符的索引
            System.out.println(s.charAt(i));    //通过索引获取每一个字符
        }
    }

统计不同类型字符个数:

public class Test2 {
    /**
     * 需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数。 ABCDEabcd123456!@#$%^
     * 分析:字符串是由字符组成的,而字符的值都是有范围的,通过范围来判断是否包含该字符 如果包含就让计数器自增
     */
    public static void main(String[] args) {
        String s = "ABCDEabcd123456!@#$%^";
        int big = 0;
        int small = 0;
        int num = 0;
        int other = 0;
        // 1、获取每一个字符,通过for循环遍历
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i); // 通过索引获取每一个字符
            // 2、判断字符是否在这个范围内
            if (c >= 'A' && c <= 'Z') {
                big++; // 如果满足是大写字母,就让其对应的变量自增
            } else if (c >= 'a' && c <= 'z') {
                small++;
            } else if (c >= '0' && c <= '9') {
                num++;
            } else {
                other++;
            }

        }
        // 3、打印每一个计数器的结果
        System.out.println(s + "中大写字母有:" + big + "个,小写字母有:" + small + "个,数字字符有:" + num + "个,其他字符有:" + other + "个");
    }

String类的转换功能:

byte[ ] getBytes():把字符串转换为字节数组

char[ ] toCharArray():把字符串转换为字符数组

static String valueOf(char[ ] chs):把字符数组转成字符串

static String valueOf(int i):把int类型的数据转成字符串

注意:String类的valueOf方法可以把任意类型的数据转成字符串

String toLowerCase():把字符串转成小写

String toUpperCase():把字符串转成大写

String concat(String str):把字符串拼接

    private static void demo3() {
        char[] arr = {'a','b','c'};
        String s = String.valueOf(arr);//底层是由string类的构造方法完成的
        System.out.println(s);
        
        String s2 = String.valueOf(100);//将100转换成字符串
        System.out.println(s2 + 100);
    }

    private static void demo2() {
        String s1 = "hello";
        char[] arr = s1.toCharArray();        //将字符串转换为字符数组
        
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void demo1() {
        String s1 = "abc";
        byte[] arr1 = s1.getBytes();
        for (int i = 0; i < arr1.length; i++) {
            //System.out.print(arr1[i] + " ");
        }
        
        String s2 = "我爱学习";
        byte[] arr2 = s2.getBytes();              //通过gdk码表将字符串转换成字节数组
        for (int i = 0; i < arr2.length; i++) {    //编码:把我们看得懂的转换成计算机读得懂的
            //System.out.print(arr2[i] + " ");    //gdk码表一个中文代表两个字节
        }                                        //gdk码表特点,中文的第一个字节肯定是负数
        
        String s3 = "琲";
        byte[] arr3 = s3.getBytes();
        for (int i = 0; i < arr3.length; i++) {
            System.out.print(arr3[i] + " ");
        }
    }

 链式编程:

public class Test3 {
    /**
     * 需求:把一个字符串的首字母转换成大写,其余为小写
     * 链式编程:只要保证每次调用完方法返回的是对象,就可以继续调用
     */
    public static void main(String[] args) {
        String s1 = "woaiXuEXiya";
        String s2 = s1.substring(0, 1).toUpperCase().concat(s1.substring(1).toLowerCase());
        System.out.println(s2);
    }

 把数组转成字符串:

public class Test4 {
    /**
     * 需求:把数组中的数据按照指定个格式拼接成一个字符串
        * 举例:
        * int[] arr = {1,2,3};    
        * 输出结果:
        * "[1, 2, 3]"
        * 分析:
        * 1、需要定义一个字符串”[“
        * 2、遍历数组获取每一个元素
        * 3、用字符串与数组中的元素进行拼接
     */
    public static void main(String[] args) {
        int[] arr = {1,2,3};
        String s = "[";
        
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                s = s +arr[i] + "]";
            }else {
                s = s +arr[i] + ", ";
            }
            
        }
        System.out.println(s);
        
    }

 字符串反转:

public class Test5 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);        //创建键盘录入对象
        System.out.println("");
        String line = sc.nextLine();                //将键盘录入的字符串存储在line中
        
        char[] arr = line.toCharArray();            //将字符串转换为字符数组
        
        String s = "";
        for (int i = 0; i < arr.length; i++) {        //倒看遍历字符数组
            s = s + arr[i];                            //拼接成字符串
        }
        System.out.println(s);
    }

猜你喜欢

转载自www.cnblogs.com/clqbolg/p/10903499.html
今日推荐