Java中字符串常见题之String相关讲解
String类的定义
在Java中,String是一个类,它代表字符串类型。
String类是final类,它是Java的内置类之一,也是Java程序中最常用的类之一。
String的常用方法
创建字符串对象
- 直接赋值
java
String str1 = "Hello World";
- 构造函数
java
String str2 = new String("Hello World");
字符串的常见操作
求字符串的长度
使用length()方法可以获得字符串的长度。
String str = "Hello World";
int len = str.length(); // len = 11
判断字符串是否为空
使用isEmpty()方法判断字符串是否为空。如果字符串长度为0,则返回true,否则返回false。
String str = "";
if (str.isEmpty()) {
System.out.println("字符串为空");
}
判断字符串是否相等
在Java中,使用equals()方法判断两个字符串是否相等。要注意的是,Java中的字符串比较必须使用equals()方法,不能使用==运算符。
String str1 = "Hello";
String str2 = "hello".toUpperCase();
if (str1.equals(str2)) {
System.out.println("字符串相等");
}
查找子串
使用indexOf()方法可以查找子串在字符串中出现的位置,如果找不到,返回-1。该方法还有一个重载版本,可以指定起始位置。
String str = "Hello World";
int pos1 = str.indexOf("World"); // pos1 = 6
int pos2 = str.indexOf("Java"); // pos2 = -1
截取子串
使用substring()方法可以截取子串,其中第一个参数是起始位置,第二个参数是结束位置(不包含结束位置的字符)。
String str = "Hello World";
String substr = str.substring(6, 11); // substr = "World"
示例说明
示例一:字符串截取
下面的代码演示了如何截取一个字符串中的子串。
String str = "Hello World";
String substr = str.substring(6, 11); // substr = "World"
System.out.println(substr);
输出结果:
World
示例二:查找子串
下面的代码演示了如何查找一个字符串中的子串。
String str = "Hello World";
int pos = str.indexOf("World");
if (pos != -1) {
System.out.println("字符串中包含子串World");
} else {
System.out.println("字符串中不包含子串World");
}
输出结果:
字符串中包含子串World
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java中字符串常见题之String相关讲解 - Python技术站