溫馨提示×

Java的indexof函數有哪些使用技巧

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

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

  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. 不區分大小寫
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. 使用負數參數
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,因為"Java"不在字符串中
  1. 鏈式調用
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("world", 8);
System.out.println(index);  // 輸出19

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女