学习Java?你得明白String方法!
- public boolen isEmpty()
- public int length()
- public char charAt(int index)
- Java String indexOf() 方法
- Java lastIndexOf() 方法
- public String concat(String s)
- public boolean endsWith(String suffix)
- public boolean startsWith(String prefix)
- 字符串的比较方法
- public String toString()
- public string substring(int beginIndex) 和 public string substring(int beginIndex, int endIndex)
- public string toLowerCase() 和 public string toUpperCase()
- public string trim()
String方法有很多。读者可以自行查看 Java String API 文档学习运用。下面介绍笔者在学习过程中遇到的一些常用的字符串方法~
public boolen isEmpty()
该方法用于判定字符串是否为空串。例如,一个字符串类型变量a的值为""。显然,a.isEmpty()为true。这里要强调的是,a是空串,但a的值不是null。
public int length()
该方法返回了制定字符串的长度。
public char charAt(int index)
该方法用于返回指定索引处的字符。在Java中,索引范围为0到length-1。比如,一个String类型的变量a的值为“ILoveJava”,那么a.charAt(2)的结果自然为字符‘o’。
Java String indexOf() 方法
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
Java lastIndexOf() 方法
public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。
public String concat(String s)
该方法用于将指定的字符串参数连接到字符串上。比如,一个String类型的变量a的值为“ILoveJava”,另一个String类型的变量b的值为“VeryMuch”。那么a.concat(b)的结果为“ILoveJavaVeryMuch”。
public boolean endsWith(String suffix)
该方法用于测试字符串是否以指定的后缀结束,比如,一个String类型的变量a的值为“ILoveJava”,一个String类型的变量b的值为“VeryMuch”,另一个String类型的变量c的值为为“ILoveJavaVeryMuch”。那么c.endsWith(b)为true,而c.endswith(a)为false。
public boolean startsWith(String prefix)
该方法用于测试字符串是否以指定的前缀结束,比如,一个String类型的变量a的值为“ILoveJava”,一个String类型的变量b的值为“VeryMuch”,另一个String类型的变量c的值为为“ILoveJavaVeryMuch”。那么c.startsWith(a)为true,而c.startswith(b)为false。
字符串的比较方法
public boolean equals(Object anObject)
此方法默认比较两个字符串的内容****是否相同,注意,这里和一般对象间的equals方法有所差异。
public boolean equalsIgnoreCase(String anotherString)
此方法弱化了比较的条件。在比较两个字符串的内容时,忽略大小写。
public String toString()
该方法用于返回该对象本身(它已经是一个字符串)
public string substring(int beginIndex) 和 public string substring(int beginIndex, int endIndex)
该方法用于返回从指定索引开始到结束(不包含结束索引)的子字符串。比如,一个String类型的变量a的值为“ILoveJava”,a.substring(2)=“oveJava”,a.substring(1,3)=“Lo”。
public string toLowerCase() 和 public string toUpperCase()
该方法用于将字符串的字母全部转化为大/小写。
public string trim()
该方法用于去除字符串首尾的空白字符。比如,一个String类型的变量a的值为“ ILoveJava ”,a.trim()的值为“ILoveJava”。