前言
接下来我们进入到String类的学习,这个类可以说是学习java的时候至关重要的基础类
范例
1.String类的概念
- String类又称作不可变字符序列
- String位于java.lang包中,之前我们一直去使用,java默认导入
- java字符串就是unicode字符序列
- java没有内置的字符串类型,而是在标准java类库中提供了预定义的类String,每个用双括号括起来的字符串就是其实例
- java中允许使用符号“+”将两个字符串连接起来
String str1 = "张三";
String str2 = new String("李四");
String str3 = "欢迎"+str2;
2.String类常用方法(重要)
要想知道有哪些String类的常用方法,我们需要读取java的API文档(我的资源中已经上传了,大家可下载):
官方网址:https://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downloads-2133158.html
我就以下载java jdk1.8 API文档为例
解压后打开以下路径即可../jdk-8u181-docs-all/docs/api/index.html,展示为以下页面。
在API文档上找到我们的String类-->java.lang.String
不难发现,String类有如下常用方法,我们从头观察,取其中重要的说一下(建议大家读英文版API文档):
- public char charAt(int index):返回该字符串的指定索引处的字符值
- public int compareTo(String anotherString):返回参与比较的两个字符串前后的ASCII码差值,用来做字符串大小比较。相等则返回0,小于则返回负数,大于则返回正数。
- public int compareToIgnoreCase(String anotherString):方法功能同上,只不过是忽略大小写
- public String concat(String str):用来进行两个字符串连接,等价于“+”
- public boolean contains(CharSequence s):比较一个字符串是否包含另外一个字符串
- pubic boolean endsWith(String stuffix):判断指定字符串是否以另一个字符串结尾
- public boolean equals(Object anObject):用来判断两个字符串的内容是否一致
- public boolean equalsIgnoreCase(Object anObject):用来判断两个字符串的内容是否一致,忽略大小写
- public int indexOf(String str):从前开始查找,返回指定字符串str在原字符串的索引位置
- public int indexOf(String str,int formIndex):从指定索引之后开始查找,返回指定字符串str在原字符串的索引位置
- public int lastIndexOf(String str):从后开始查找,返回指定字符串str在原字符串的索引位置
- public int lastIndexOf(String str,int formIndex):从指定索引之前开始查找,返回指定字符串str在原字符串的索引位置
- public boolean isEmpty():判断一个字符串是否为空串,即“”
- pubic int length():返回指定字符串的长度
- public String replace(charSequence target,charSequence replacement):对字符串指定子串进行替换,基于字符串替换
- public String replaceAll(String regex,String replacement):对字符串指定子串进行替换,基于正则表达式替换
- public String replaceFirst(String regex,String replacement):对字符串中指定子串第一项进行替换,基于正则表达式替换
- public String[] split(String regex):将字符串根据指定字串进行拆分形成字符串数组,基于正则表达式
- public String[] split(String regex,int limit):将字符串根据指定字串进行拆分形成字符串数组,进行limit次拆分,若limit小于等于零,那么进行无限次拆分,直至拆分结束,基于正则表达式
- public boolean startsWith(String prefix):判断指定字符串是否以另一个字符串开头
- public boolean startsWith(String prefix,int toffset):从指定索引向后查找,判断指定字符串是否以另一个字符串开头
- public String substring(int beginIndex):从指定索引处进行字符串截取
- public String substring(int beginIndex,int endIndex):从指定索引范围进行字符串截取
- public String toLowerCase():将指定字符串转化为小写(一般用于英文字符串)
- public String toUpperCase():将指定字符串转化为大写(一般用于英文字符串)
- public String trim():将指定字符串去除空格,制表符等
- public static String valueOf(其他类型数据):将其他类型数据转化为字符串数据
- public String toString():同上