版本说明:JDK1.8
博客中图片来源说明:课程上老师的PPT
String主要的相关方法学习路径,如下。
脑图
String类常用方法使用 一
String类常用方法使用 二
String类常用方法使用 三
1.定义
String为开发过程中经常遇到的类,本博客主要针对String常用方法进行记录,内容偏简单。
String类源码的定义如下
String类由final关键字定义可知:String类型不可以被继承。
JDK文档类的结构
在Java语言中将字符串作为对象进行管理,因此可以像创建一样来创建字符串对象;
1.1String类的构造方法
示例代码:将ISO8859-1字符串转化成GB2312编码
String类源码中的构造函数
public String(byte bytes[], String charsetName)
throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
}
package com.mark.TestOther;
import java.io.UnsupportedEncodingException;
public class StingTest {
public static void main(String[] args){
try {
//getBytes(Charser charset):把字符串按照指定的编码来得到字符数组。
String s = new String("Test".getBytes("ISO8859-1"),"GB2312");
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
2.String类中常用的方法
2.1字符串的长度:length()
length():方法返回的字符串中的字符的个数
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello");
System.out.println(s1.length());
}
}
运行结果:
5
补充:length()方法返回的字符串的长度包括字符串中的空格。
2.2连接多个字符串:“+”
使用“+”运算符可以实现连接多个字符串的功能。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("word");
String s = s1+s2;
System.out.println(s);
}
}
运行结果
helloword
2.3连接其他数据类型
字符串也可以同其他基本数据类型进行连接。如果将字符串同这些数据类型进行连接,会将这些数据直接转换成字符串。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello");
int i = 4;
float f= 2.5f;
String s = s1+i+f;
System.out.println(s);
}
}
运行结果
hello42.5
代码中变量i和f都不是字符串,但是当它们和字符串相连时会自动调用toString()方法,将其装换成String类型,然后再参与连接。
2.4字符串查找
String类提供了两种查找字符串的方法
- indexOf(): 该方法返回的搜索的字符或者搜索的字符串首次出现的位置
- lastIndexOf():该方法返回的搜索的字符或者搜索的字符串最后一次出现的位置
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello");
int i = s1.indexOf("l");
System.out.println("第一次出现字符串“l”的位置是:"+i);
i = s1.lastIndexOf('l');
System.out.println("最后次出现字符‘l’的位置是:"+i);
i = s1.indexOf("b");
System.out.println("第一次出现字符串“b”的位置是:"+i);
}
}
运行结果:
第一次出现字符串“l”的位置是:2
最后次出现字符‘l’的位置是:3
第一次出现字符串“b”的位置是:-1
如果lastIndexOf()方法中的参数空字符串“”(注意没有空格),则返回的结果是leng()返回的结果一样。如下代码所示:
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word");
System.out.println("字符串的长度是:"+s1.length());
System.out.println("空字符串的最后索引位置是:"+s1.lastIndexOf(""));
}
}
运行结果:
字符串的长度是:10
空字符串的最后索引位置是:10