Java_认识String类

C 语言中已经涉及到字符串了,但是在 C 语言中要表示字符串只能使用字符数组或者字符指针,
可以使用标准库提 供的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分离开
的方式不符合面相对象的思想,而字符串应用又非常广泛,因此Java 语言专门提供了 String

一、 常用方法

1.1 构造方法

String 类提供的构造方式非常多,常用的有以下三种

public static void main(String[] args) {
        String s1 = "hello world!";
        System.out.println(s1);
        //    直接常量串构造
        String s2 = new String("hellohellohello!");
        System.out.println(s2);
        //new一个
        char[] arr = {'h', 'e', 'l', 'l', 'o'};
        String s3 = new String(arr);
        System.out.println(s3);
        //    使用字符数组构造
    }

需要注意的是 String 是引用数据类型,内部并不存储字符串本身

Java “” 引起来的也是 String 类型对象。
 public static void main(String[] args) {
        System.out.println("hello".length());
    }

1.2 字符串比较

Java 中提供了4种比较方式

1.2.1 == 比较是否引用同一个对象

因为 String 属于引用数据类型,== 比较的是引用的地址

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);
    }

1.2.2 boolean equals(按照字典序比较 )

String 类重写了父类 Object  equals 方法,Object  equals 默认按照 == 比较,String 重写

equals 方法

public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1.equals(s2));
    }

1.2.3 int compareTo(String s) 方法: 按照字典序进行比较

String 类中实现了 Comparable 接口

实现了 compareTo 方法

比较方法类似于 C语言 中的 strcmp

先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
如果前 k 个字符相等 (k 为两个字符长度最小值 ) ,返回值两个字符串长度差值
 public static void main(String[] args) {
        String s1 = new String("helloa");
        String s2 = new String("hellob");
        String s3 = new String("hello123456");
        String s4 = new String("hello");
        System.out.println(s1.compareTo(s2));
        System.out.println("================");
        System.out.println(s3.compareTo(s4));
    }

1.2.4 int compareToIgnoreCase(String str)

compareTo方式相同,但是忽略大小写比较

   public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("ABC");
        String s3 = new String("ABc");
        String s4 = new String("aBC");
        System.out.println(s1.compareToIgnoreCase(s2));
        System.out.println(s1.compareToIgnoreCase(s3));
        System.out.println(s1.compareToIgnoreCase(s4));
    }

1.3 字符串查找

String 类提供的常用查找的方法:
方法 功能
char charAt(int index)
返回 index 位置上字符,如果 index 为负数或者越界,抛出 ndexOutOfBoundsException异常
int indexOf(int ch)
返回 ch 第一次出现的位置,没有返回 -1
int indexOf(int ch, int fromIndex)
fromIndex 位置开始找
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值