溫馨提示×

Java的indexof函數(shù)有哪些使用技巧

小樊
81
2024-09-30 00:43:18
欄目: 編程語言

在Java中,indexOf函數(shù)是String類的一個重要方法,用于查找指定字符或子字符串在字符串中首次出現(xiàn)的位置。以下是一些使用indexOf函數(shù)的技巧:

  1. 基本用法
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index);  // 輸出7
  1. 從指定位置開始查找
String str = "Hello, World! World!";
int index = str.indexOf("World", 8);  // 從第8個位置開始查找
System.out.println(index);  // 輸出19
  1. 查找子字符串
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index);  // 輸出7
  1. 不區(qū)分大小寫
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("WORLD");
System.out.println(index);  // 輸出7
  1. 查找多個子字符串
String str = "Hello, World! World!";
int index1 = str.indexOf("World");
int index2 = str.indexOf("World", index1 + 5);  // 在第一個"World"之后5個位置開始查找
System.out.println(index1);  // 輸出7
System.out.println(index2);  // 輸出19
  1. 使用負(fù)數(shù)參數(shù)
String str = "Hello, World!";
int index = str.indexOf("World", -1);  // 從字符串末尾開始向前查找
System.out.println(index);  // 輸出7
  1. 未找到子字符串時的返回值
String str = "Hello, World!";
int index = str.indexOf("Java");
System.out.println(index);  // 輸出-1,因?yàn)?quot;Java"不在字符串中
  1. 鏈?zhǔn)秸{(diào)用
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("world", 8);
System.out.println(index);  // 輸出19

這些技巧可以幫助你更有效地使用Java中的indexOf函數(shù)。

0