字符串替换:
如:
//替换(replace)
public static void fun1(){
String string = "zengzeleiwo";
String string1=string.replace('o','a');
System.out.println(string1);//结果:zengzeleiwa
String string2 = string.replace("ng","chinese");//结果:zechinesezeleiwo
}
字符串拼接和包含:
如:
public static void fun2(){
//包含(contains)
String str1 = "zengzelei";
boolean b1 = str1.contains("en");
System.out.println(b1);//结果为true
//拼接字符串(concat)
String str2 = "leishao";
String str3 = str1 + str2;
String str4 = str1.concat(str2);
System.out.println(str3);//结果为:zengzeleileishao
System.out.println(str4);//结果为:zengzeleileishao
}
字符串分割:
如:
public static void fun2(){
String string = "数学,语文,计算机,体育"
//分割(split)
String [] array = String.split(",");
for(String str : array){
System.out.print(str + " ");//输出结果为:数学 语文 计算机 体育
}
}
字符串剪切:
如:
//剪切(subString)
public static void fun3(){
String string = "zengzelei";
//返回从索引往后的字符串
String string1 = string.subString(5);//输出结果为:elei
String string2 = string.subString(2,6)//输出结果为:ngze
}
字符串的大小写转换:
// 转换大小写(toUpperCase)
public static void fun4(){
String string = "wanglong";
// 转大写
String string1 = string.toUpperCase();
String string2 = "CHINESE";
// 转小写(toLowerCase)
String string3 = string2.toLowerCase();
System.out.println(string1); //输出结果:WANGLONG
System.out.println(string3); //输出结果:chinese
}
等号与字符串equals用法:
如:
//等号的用法(=)
public class StringComparision1 {
public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob");
String name3 = "Bob";
// 1st case
if (name1 == name2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1 == name3) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}
//equals(相当与等号)
public class StringComparision2 {
public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob1");
String name3 = "Bob";
// 1st case
if (name1.equals(name2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1.equals(name3)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}
网友评论