Java学习——常用类的学习之String类

Java学习——常用类的学习之String类

1.String类

  • 字符串:
    -String类是对字符串进行操作的一个类,那么我们先简单来了解一下什么是字符串,字符串是由多个字符组成的字符序列,字符串可以看成字符数组。
  • String的概述:
    String 类代表字符串。Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
    字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。
  • String的构造方法:
    A:常见构造方法
    public String():空参构造
    public String(byte[] bytes):把字节数组转成字符串
    public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串(index:表示的是从第几个索引开始, length表示的是长度)
    public String(char[] value):把字符数组转成字符串
    public String(char[] value,int index,int count):把字符数组的一部分转成字符串
    public String(String original):把字符串常量值转成字符串
  • 定义字符串的两种方法:
    1.String str = new String(“abc”);
    2.String str2 = “aaa”;
  • 注意:
    1.字符串是常量,他们的值在创建之后不能改变
    2.String类默认重写了toString()方法
    3.字符串字面值如:"abc"都是String类的一个实现,可以直接打点调用方法。如:
		//获取字符串的长度
        int i = "abc".length();
        System.out.println(i);
  • String中的判断功能:
    public boolean equals(Object obj): 比较字符串的内容是否相同,区分大小写
    public boolean equalsIgnoreCase(String str): 比较字符串的内容是否相同,忽略大小写
    public boolean contains(String str): 判断字符串中是否包含传递进来的字符串
    public boolean startsWith(String str): 判断字符串是否以传递进来的字符串开头
    public boolean endsWith(String str): 判断字符串是否以传递进来的字符串结尾
    public boolean isEmpty(): 判断字符串的内容是否为空串""。
  • String中的获取功能:
    public int length(): 获取字符串的长度。
    public char charAt(int index): 获取指定索引位置的字符
    public int indexOf(int ch): 返回指定字符在此字符串中第一次出现处的索引。
    public int indexOf(String str): 返回指定字符串在此字符串中第一次出现处的索引。
    public int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
    public int indexOf(String str,int fromIndex): 返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
    可以顺带提一下lastIndexOf系列
    public String substring(int start): 从指定位置开始截取字符串,默认到末尾。
    public String substring(int start,int end): 从指定位置开始到指定位置结束截取字符串。
  • 遍历字符串:
public class Test {
    public static void main(String[] args) {
        String str = "hello";
        //遍历字符串
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
        }
    }
}
/*
	输出结果:
			h
			e
			l
			l
			o
*/
  • String中的转换功能:
    public byte[] getBytes(): 把字符串转换为字节数组。
    public char[] toCharArray(): 把字符串转换为字符数组。
    public static String valueOf(char[] chs): 把字符数组转成字符串。
    public static String valueOf(int i): 把int类型的数据转成字符串。
    注意:String类的valueOf方法可以把任意类型的数据转成字符串。
    public String toLowerCase(): 把字符串转成小写。
    public String toUpperCase(): 把字符串转成大写。
    public String concat(String str): 把字符串拼接。
    • String中的其他功能:
      public String replace(char old,char new) 将指定字符进行互换
      public String replace(String old,String new) 将指定字符串进行互换
      public String trim() 去除两端空格
      public int compareTo(String str) 会对照ASCII 码表 从第一个字母进行减法运算 返回的就是这个减法的结果,如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果,如果连个字符串一摸一样 返回的就是0
      public int compareToIgnoreCase(String str) 跟上面一样 只是忽略大小写的比较

猜你喜欢

转载自blog.csdn.net/qq_43411550/article/details/89634867