Java:获取字符串中匹配位置的方法? [英] Java: method to get position of a match in a String?

查看:41
本文介绍了Java:获取字符串中匹配位置的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?

推荐答案

执行此操作的方法系列是:

The family of methods that does this are:

  • int indexOf(String str)

    返回此字符串中第一次(或最后)出现的指定子字符串的索引[从指定索引开始向前(或向后)搜索].

    Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].

    <小时>

    String text = "0123hello9012hello8901hello7890";
    String word = "hello";
    
    System.out.println(text.indexOf(word)); // prints "4"
    System.out.println(text.lastIndexOf(word)); // prints "22"
    
    // find all occurrences forward
    for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
        System.out.println(i);
    } // prints "4", "13", "22"
    
    // find all occurrences backward
    for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
        System.out.println(i);
    } // prints "22", "13", "4"
    

    这篇关于Java:获取字符串中匹配位置的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆