5.3 String类 1.查看String类的说明 (1)字符串字面值“abc”也可以看做是一个字符串对象; (2)字符串是常量,一旦被赋值,就不能被改变; (3)除非另行说明,否则将 null 参数传递给此类中的构造方法或方法将抛出 NullPointerException(空指针异常); 2.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):把字符数组的一部分转换为字符串; 3.String类的判断功能 boolean equals(Object obj): 比较字符串的内容是否相同,区分大小写 boolean equalsIgnoreCase(String str): 比较字符串内容是否相同,忽略大小写 boolean contains(String str): 判断大字符串中是否包含小字符串 boolean startsWith(String str): 判断字符串是否以某个指定的字符串开头 boolean endsWith(String str): 判断字符串是否以某个指定的字符串结尾 boolean isEmpty(): 判断字符串是否为空。 4.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): 从指定位置开始到指定位置结束截取字符串。*含头不含尾. 5.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): 把字符串拼接。 6.String的替换功能及案例演示 String replace(char old,char new) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 String replace(String old,String new) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 String trim() 返回字符串的副本,忽略前导空白和尾部空白.
|