簡體   English   中英

Java 獲取兩個索引之間的 Substring

[英]Java Get Substring Between Two Indexes

例如我有這個字符串: Hello, world! 我想通過使用索引來Hello 有沒有function之類的

package com.example;

import static java.lang.String.getStringBetweenIndex;

public class Example {
    public static void main(String[] args) {
        String hello = "Hello, world!";

        System.out.println(hello.getStringBetweenIndex(0, 5));
    }
}

這給了 output Hello

public String substring​(int beginIndex, int endIndex)

返回一個字符串,該字符串是該字符串的 substring。 substring 從指定的 beginIndex 開始並延伸到索引 endIndex - 1 處的字符。因此 substring 的長度是 endIndex-beginIndex。 例子:

  • "hamburger".substring(4, 8)返回 "urge"
  • "smiles".substring(1, 5)返回 "mile"

參數:

  • beginIndex - 起始索引,包括在內。
  • endIndex - 結束索引,獨占。

回報:

  • 指定的 substring。

拋出:

  • IndexOutOfBoundsException - 如果 beginIndex 為負數,或者 endIndex 大於此字符串 object 的長度,或者 beginIndex 大於 endIndex。

來源: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)

您可以使用*.substring(firstIndex, secondIndex); 方法。 嘗試;

package com.example;

public class Example {
    public static void main(String[] args) {
        String hello = "Hello, world!";

        System.out.println(hello.substring(0, 5));
    }
}

返回一個字符串,該字符串是該字符串的 substring。 substring 從指定的 beginIndex 開始並延伸到索引 endIndex - 1 處的字符。因此 substring 的長度是 endIndex-beginIndex。 例子:

  • "hamburger".substring(4, 8)返回 "urge"
  • "smiles".substring(1, 5)返回 "mile"

參數:

  • beginIndex - 起始索引,包括在內。
  • endIndex - 結束索引,獨占。

回報:

指定的 substring。

拋出:

  • IndexOutOfBoundsException - 如果 beginIndex 為負數,或者 endIndex 大於此字符串 object 的長度,或者 beginIndex 大於 endIndex。

來源: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM