首頁 > Java > 主體

在 String Java 中尋找給定單字後的特定單字索引

WBOY
發布: 2024-02-22 13:40:07
轉載
1025 人瀏覽過

在Java程式設計中,尋找給定單字後的特定單字索引是一個常見問題。在String類別中,有多種方法可以實現這項功能。本文將透過具體案例示範如何在Java中使用這些方法來尋找目標單字並取得其索引位置。讓我們一起跟著php小編蘋果的指導,深入了解這項實用的技巧。

問題內容

假設我有字串

String str = "Hello all, the world is going to end here and I am the only end character which is in the end game of the end world";
登入後複製

現在我想寫一個函數,在其中傳遞整個字串、matchingword、wordtofindaftermatchingword

所以假設我想找到“game”的索引,但是“game”單字應該在“end”單字之後,並且“end”單字可以在 string 中出現 n 次。我不想使用正規表示式,因為我正在考慮使這個函數通用。

解決方法

正如有人所說,您可以使用帶有起始索引的方法indexof(string,int):

public static int indexof(string str, string word, string precededby) {
    int i = str.indexof(precededby);
    if (i < 0) {
        return -1;
    }
    return str.indexof(word, i+precededby.length());
}
登入後複製

現在這個:

System.out.println(indexOf(str, "game", "end"));
登入後複製

將列印 94

以上是在 String Java 中尋找給定單字後的特定單字索引的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!