相信大家在刚学习java时很快就接触到字符串输出,以下有几个字符串输出方法可供大家参考:
1.比较字符串大小:
public class Main {
public static void main(String
[] args
) {
int com
;
String str1
= "China";
String str2
= "CHINA";
com
= str1
.compareTo(str2
);
System
.out
.println(com
);
com
= str1
.compareToIgnoreCase(str2
);
System
.out
.println(com
);
}
}
输出结果:
32 0
2.连接字符串
public class Main {
public static void main(String
[] args
) {
String str1
= "China";
String str2
= "CHINA";
String str3
;
System
.out
.println(str1
.concat(str2
));
System
.out
.println(str1
.concat(" i love you!"));
System
.out
.println(str1
+ " i love you!");
}
}
输出结果:
ChinaCHINA China i love you! China i love you!
3.字符串返回指定索引处的 char 值
public class Main {
public static void main(String
[] args
) {
String str_1
= "china";
char chars
= str_1
.charAt(3);
System
.out
.println("chars = " + chars
);
}
}
输出结果:
chars = n
4.用码数或者字符串的形式搜索字符串位置
public class Main {
public static void main(String
[] args
) {
String str1
= "China";
int num1
= str1
.indexOf(1);
System
.out
.println("num = " + num1
);
int num2
= str1
.indexOf("ina");
System
.out
.println("num2 = " + num2
);
int num3
= str1
.indexOf("C", 0);
System
.out
.println("num3 = " + num3
);
}
}
num1 = -1 num2 = 2 num3 = 0
5.其他
public class Main {
public static void main(String
[] args
) {
String str1
= " China ";
int num1
= str1
.length();
System
.out
.println("num1 = " + num1
);
String str2
= str1
.replace("hina","HINA");
System
.out
.println("str2 = " + str2
);
String str3
= str2
.substring(0,5);
System
.out
.println("str3 = " + str3
);
String str4
= str1
.toLowerCase();
System
.out
.println("str4 = " + str4
);
String str5
= str1
.toUpperCase();
System
.out
.println("str5 = " + str5
);
String str6
= str1
.trim();
System
.out
.println("str6 = " + str6
);
String str7
= str1
.join(" is"," my"," home",", i love it");
System
.out
.println("str7 = " + str7
);
}
}
num1 = 7 str2 = CHINA str3 = CHIN str4 = china str5 = CHINA str6 = China str7 = my is home is, i love it