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/zh-tw/n/282941.html