Java 中的 String 类包含了 50 多个方法,绝大多数方法都很有用,下面记录了一些最常用的方法。
【说明:第一个为方法返回类型,接着为方法名,括号内为方法参数;后如有版本号,表示在此版本之后才支持的方法】
- char charAt(int index)
返回指定位置的代码单元。除非对底层代码感兴趣,否则不需要调用这个方法。并且这个方法存在隐患
- int codePointAt(int index) 5.0
返回从给定位置开始或结束的代码点
- int offsetByCodePoints(int startIndex, int cpCount) 5.0
返回从 startIndex 代码点开始,位移 cpCount 后的代码点索引
- int compareTo(String other)
按照字典顺序,如果字符串位于 other 之前,则返回一个负数;如果字符串位于 other 之后,则返回一个正数;如果两个字符串相等,则返回零
- boolean endsWith(String suffix)
如果字符串是以 suffix 结尾,则返回 true
- boolean equals(Object other)
如果字符串与 other 相等,则返回 true
- boolean equalsIgnoreCase(String other)
如果字符串与 other 相等(不区分大小写),则返回 true
- int indexOf(String str)
- int indexOf(String str, int fromIndex)
- int indexOf(int cp)
- int indexOf(int cp, int fromIndex)
返回与字符串 str 或代码点 cp 匹配的第一个子串的开始位置,该位置从索引 0 或者 fromIndex 开始计算。如果在原始字符串中不存在 str,则返回 -1.
- int lastIndexOf(String str)
- int lastIndexOf(String str, int fromIndex)
- int lastIndexOf(int cp)
- int lastIndexOf(int cp, int fromIndex)
返回与字符串 str 或代码点 cp 匹配的最后一个子串的开始位置,该位置从原始字符串尾端或 fromIndex 开始计算。
- int length(String str)
返回字符串的长度
- int codePointCount(int startIndex, int endIndex) 5.0
返回 startIndex 和 endIndex - 1 之间的代码点数量。没有匹配成对的替代字符作为代码点计算。
- String replace(CharSequence oldString, CharSequence newString)
返回一个新字符串,该字符串用 newString 代替原始字符串中所有的 oldString。可以用 String 或 StringBuilder 对象作为 CharSequence 参数
- boolean startsWith(String prefix)
如果字符串以 prefix 字符串开始,则返回 true
- String substring(int beginIndex)
- String substring(int beginIndex, int endIndex)
返回一个新字符串,该串包含包含从原始字符串 beginIndex 到串尾或 endIndex - 1 的所有代码单元
- String toLowerCase()
返回一个新字符串,将原始字符串中的所有大写字母转换为小写字母
- String toUpperCase()
返回一个新字符串,将原始字符串中的所有小写字母转换为大写字母
- String trim()
返回一个新字符串,该字符串删除了原始字符串中头部与尾部的空格