Linux 拨号vps windows公众号手机端

string怎么查找某个字符串的位置

lewis 9年前 (2016-10-10) 阅读数 11 #程序编程
文章标签 String

要查找某个字符串在另一个字符串中的位置,可以使用字符串的indexOf方法。该方法返回要查找的子字符串在父字符串中第一次出现的位置,如果没有找到则返回-1。

例如,我们要查找字符串"hello"在另一个字符串"hello world"中的位置可以这样做:

String str = "hello world";
String subStr = "hello";

int index = str.indexOf(subStr);
if (index != -1) {
    System.out.println("子字符串在父字符串中的位置是:" + index);
} else {
    System.out.println("未找到子字符串");
}

上述代码将会输出:子字符串在父字符串中的位置是:0,表示"hello"在"hello world"中从第0个位置开始出现。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门