Java程式設定顯示子字串的範圍
在本文中,我們將學習如何使用Java中的substring()方法從字串中提取特定範圍的字元。substring(int beginIndex, int endIndex)方法 獲取字串的一部分,從beginIndex開始,到endIndex之前結束。
問題陳述
給定一個字串,從指定的索引範圍內提取子字串。
輸入
String: pqrstuvw
輸出
Substring: stu
設定顯示子字串範圍的步驟
以下是設定顯示子字串範圍的步驟:
- 宣告一個字串str。
- 用值“pqrstuvw”初始化字串str。
- 使用substring(int beginIndex, int endIndex)方法從索引中提取字元。
- 列印輸出
Java程式設定顯示子字串的範圍
以下是一個完整的示例,其中我們設定了從字串中顯示子字串的範圍:
public class Demo { public static void main(String[] args) { String str = "pqrstuvw"; System.out.println("String: "+str); // range from 3 to 6 String strRange = str.substring(3, 6); System.out.println("Substring: "+strRange); } }
輸出
String: pqrstuvw Substring: stu
程式碼解釋
在程式碼中,我們將使用substring()方法設定字串的子字串範圍。假設我們的字串如下:
String str = "pqrstuvw";
str.substring(3, 6)從字串“pqrstuvw”中選擇位置3到5的字元。
String strRange = str.substring(3, 6);
這將得到子字串stu,並將其儲存在strRange中。然後,main()方法列印原始字串和提取的子字串。
廣告