Java中String是一个常用的类,对String进行包含操作是非常常见的需求。在实际开发中,我们需要判断一个字符串是否包含另一个字符串,根据包含的位置进行字符串的操作等。本文将介绍Java中String的包含操作。
一、字符串包含的基本用法
Java中提供了contains()方法用于字符串包含的判断。
/**
* 判断一个字符串是否包含另一个字符串
*/
public class StringContainsDemo {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "hello";
if (str1.contains(str2)) {
System.out.println(str1 + "包含" + str2);
} else {
System.out.println(str1 + "不包含" + str2);
}
}
}
运行结果:
hello world包含hello
contains()方法返回一个布尔值,如果被测试字符串包含在调用字符串中,则返回true。否则,返回false。
二、忽略大小写的包含判断
有时,需要进行字符串包含判断时,需要忽略字符串的大小写。Java中可以使用equalsIgnoreCase()方法进行忽略大小写的字符串比较。
/**
* 忽略大小写的包含判断
*/
public class StringContainsIgnoreCaseDemo {
public static void main(String[] args) {
String str1 = "Hello World";
String str2 = "hello";
if (str1.toLowerCase().contains(str2.toLowerCase())) {
System.out.println(str1 + "包含" + str2);
} else {
System.out.println(str1 + "不包含" + str2);
}
}
}
运行结果:
Hello World包含hello
通过将两个字符串都转换成小写字母的形式,就可以实现忽略大小写的字符串比较。
三、字符串的位置操作
在Java中,可以通过indexOf()方法获得字符串在另一个字符串中的位置。如果字符串不存在,则返回-1。
/**
* 获得字符串在另一个字符串中的位置
*/
public class StringIndexOfDemo {
public static void main(String[] args) {
String str = "hello world";
int index = str.indexOf("world");
if (index != -1) {
System.out.println("world在字符串" + str + "中的位置是:" + index);
} else {
System.out.println("字符串" + str + "中不存在world");
}
}
}
运行结果:
world在字符串hello world中的位置是:6
如果需要从指定位置开始查询字符串,则可以使用indexOf(String str, int fromIndex)方法。
/**
* 从指定位置开始查找字符串在另一个字符串中的位置
*/
public class StringIndexOfDemo {
public static void main(String[] args) {
String str = "hello world, world";
int index = str.indexOf("world", 7);
if (index != -1) {
System.out.println("world在字符串" + str + "中的位置是:" + index);
} else {
System.out.println("字符串" + str + "中不存在world");
}
}
}
运行结果:
world在字符串hello world, world中的位置是:13
substring()方法用于从字符串中获得指定位置之间的子串。
/**
* 获取从指定位置开始的子字符串
*/
public class StringSubstringDemo {
public static void main(String[] args) {
String str = "hello world";
String subStr = str.substring(6);
System.out.println(subStr);
}
}
运行结果:
world
如果需要获得指定位置之间的子字符串,则可以使用substring(int beginIndex, int endIndex)方法。
/**
* 获取指定位置之间的子字符串
*/
public class StringSubstringDemo {
public static void main(String[] args) {
String str = "hello world";
String subStr = str.substring(6, 11);
System.out.println(subStr);
}
}
运行结果:
world
四、结语
Java String包含操作是常用的字符串操作之一,在实际的开发工作中经常用到。本文介绍了Java中常用的字符串包含操作,希望对读者有所帮助。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/282941.html