在 Java 中,字符串属于对象,Java 提供了 String 类来创建和操作字符串。
如:
String str = "爱吃西瓜的番茄酱";
注意:String类是不可改变的,所以一旦创建了 String 对象,那它的值就无法改变了。
用于获取有关对象的信息的方法称为访问器方法。
String 类的一个访问器方法是 length()
方法,它返回字符串对象包含的字符数。
public class StringDemo {
public static void main(String[] args){
String site = "www.cnblogs.com/youcoding";
int len = site.length();
System.out.println("我的博客地址长度为:"+ len);
}
}
输出:
我的博客地址长度为:25
1、可以使用concat()
方法来连接字符串。
如:
"我的名字是:".concat("番茄");
结果为:
我的名字是:番茄
2、可以使用+
操作符来连接字符串:
如:
"hello " + "world "+ "!"
结果如下:
hello world !
1、可以使用printf()
方法来格式化输出。
如:
public class StringDemo {
public static void main(String[] args){
float a = 1;
int b = 2;
String c = "hello";
System.out.printf("浮点型变量的值为:%f, "+
"整数型变量的值为:%d, "+
"字符串型变量的值为:%s, ", a, b, c);
}
}
结果为:
浮点型变量的值为:1.000000, 整数型变量的值为:2, 字符串型变量的值为:hello,
Process finished with exit code 0
2、可以使用format()
方法创建可复用的格式化字符串。
如:
public class StringDemo {
public static void main(String[] args){
float a = 1;
int b = 2;
String c = "hello";
String fs;
fs = String.format("浮点型变量的值为:%f, "+
"整数型变量的值为:%d, "+
"字符串型变量的值为:%s, ", a, b, c);
System.out.println(fs);
}
}
输出:
浮点型变量的值为:1.000000, 整数型变量的值为:2, 字符串型变量的值为:hello,
Process finished with exit code 0
每天学习一点点,每天进步一点点。
原文:https://www.cnblogs.com/youcoding/p/12682291.html