一、字符串创建
创建格式:
类型 变量名 = 值
String str = "string"
二、字符串长度
长度格式:
字符串变量.length()
str.length()
public class StrLen {
public static void main(String[] args) {
String str = "string";
int len = str.length();
System.out.println("输出字符串长度:"+len);
}
}
输出结果:
输出字符串长度:6
三、字符串拼接
1、concat()拼接
string.concat(string2)
public class StrLen {
public void strCon() {
String str = "string";
System.out.println("输出的字符串是:".concat(str));
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.strCon();
}
}
2、+ 拼接
str + str2
public class StrLen {
public void strOut() {
String str = "string";
int len = str.length();
System.out.println("输出字符串长度:" + len);
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.strOut();
}
四、字符串格式化
String.format()
public class StrLen {
public void strFor() {
Object floatVar = null;
Object intVar = null;
Object stringVar = null;
String fs;
fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.strFor();
}
}
五、字符串大小写转换
toLowerCase() 方法可以将字符串中的所有字符全部转换成小写
格式:字符串名.toLowerCase()
toUpperCase() 则将字符串中的所有字符全部转换成大写
格式:字符串名.toUpperCase()
package funcdation;
public class StrLen {
public void turnStr() {
String str = "hi";
System.out.println(str.toUpperCase());
String str2 = "HELLO";
System.out.println(str2.toLowerCase());
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.turnStr();
}
}
输出结果:
HI
hello
六、字符串空格处理
去掉字符串前后空格格式:
字符串名.trim()
package funcdation;
public class StrLen {
public void stripBlank() {
String str = " !!hi";
System.out.println(str.trim().length());
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.stripBlank();
}
}
输出结果:
4
说明:前面的空格被去掉,如果没去掉的话,字符串长度为5.
七、字符串提取
1. substring(int beginIndex)
用于提取从索引位置开始至结尾处的字符串部分
2. substring(int beginIndex,int endIndex)
说明索引的起始位置到结束位置
public class StrLen {
public void getStr() {
String str = "hello,java";
System.out.println(str.substring(6));
System.out.println(str.substring(0,5));
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.getStr();
}
}
输出结果:
java
hello
八、字符串分割
分割格式:
str.split(String sign,int limit)
说明:
str 为需要分割的目标字符串
sign 为指定的分割符,可以是任意字符串
limit 表示分割后生成的字符串的限制个数,如果不指定,则表示不限制,也可不填
package funcdation;
public class StrLen {
public void getSplit() {
String str = "hello,java";
String[] s = str.split(",");
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}
public static void main(String[] args) {
StrLen str = new StrLen();
str.getSplit();
}
}
输出结果:
hello
java