字符串
(1)java中的字符串就是Unicode字符序列
(2)java中的字符串是不可变的,所以不能简单的使用索引的方式来直接修改某个位置的值。
例:将hello改为hi
String str = "hello";
//在这里不是修改了字符串的值而是改变了字符串变量str的引用,让它引用了"hi"这个字符串
str = str.substring(0,1)+"i";
System.out.println(str);
(3)检测字符串是否相等不能用"==",可以用equals方法来检测两个字符串是否相等。
String str1 = "hello";
System.out.println(str1 == "hello");//true
//注意这里比较的是地址是否相同,但是我们的本意可能是"hel"是否等于"hel"
System.out.println(str1.substring(0, 3) == "hel");//false
(4)字符串中有空串和null串
String str = null;//null串
String str1 = ""; //空串
(5)另外请注意一下:码点和代码单元(从《java核心卷(一)》中看到的概念)可以看一下这篇博客:https://blog.csdn.net/diehuang3426/article/details/83422309
字符串中的常用方法
字符串中的方法有很多,这里只是一些我个人认为比较常用的一些。
(1)int compareTo(String other )
按照字典顺序,如果字符串位于other之前,返回一个负数;如果字符串位于other之后,返回一个正数;如果两个字符串相等,返回0。
System.out.println("abc".compareTo("bcd"));//-1
System.out.println("abc".compareTo("abc"));//0
System.out.println("zbc".compareTo("acd"));//25
(2)boolean equals(Object other )
如果字符串与other相等,返回true。
(3)boolean equalsIgnoreCase(String other)
如果字符串与other相等(忽略大小写),返回true。
(4)boolean startsWith(String prefix)和boolean endsWith(String suffix)
如果字符串以prefix开头或suffix结尾,则返回true。
(5)int index0f(String str)
int index0f(String str, int fromIndex )
int index0f(int cp)
int index0f(int cp, int fromIndex )
返回与字符串str 或代码点cp匹配的第一个子串的开始位置。这个位置从索引0或fromIndex开始计算。如果在原始串中不存在str,返回-1。
(6)int lastIndex0f(String str, int fromIndex )
int lastIndex0f(int cp)
int lastindex0f(int cp,int fromIndex)
返回与字符串str或代码点cp匹配的最后一个子串的开始位置。这个位置从原始串尾端或fromIndex开始计算。
(7)int length( )
返回字符串的长度。
(8)String replace( Char Sequence o1 dString,CharSequence newString )
返回一个新字符串。这个字符串用newString代替原始字符串中所有的oldString。可以用String或StringBuilder对象作为CharSequence参数。
(9)String substring( int beginIndex)
String substring( int beginIndex, int endIndex )
返回一个新字符串。这个字符串包含原始字符串中从beginIndex到串尾或endIndex-1的所有代码单元。
(10)String toLowerCase( )和String toUpperCase( )
返回一个新字符串。这个字符串将原始字符串中的大写字母改为小写,或者将原始字符串中的所有小写字母改成了大写字母。
(11)String trim( )
返回一个新字符串。这个字符串将删除了原始字符串头部和尾部的空格。
(12)String join(CharSequence delimiter, CharSequence… elements)
返回一个新字符串,用给定的定界符连接所有元素。