【问题标题】:How to get the index of second or nth occurencece of a char without array only string class in JAVA如何在JAVA中获取没有数组仅字符串类的字符的第二次或第n次出现的索引
【发布时间】:2019-11-11 18:58:29
【问题描述】:

我正在尝试在 Java 中创建一种方法,该方法可以为我提供字符串中第 n 次出现的字符的索引。 例子 String Hello="allo 大家你好吗" 如何获得第三个“Y”的索引? 谢谢你

【问题讨论】:

标签: java string class


【解决方案1】:
final String text = "allo every body how are you";
int n = 3;
final char toFind = 'y';

int index = 0;
while (index < text.length()) {
  if (text.charAt(index) == toFind) {
    n--;
    if (n == 0)
      break;
  }
  index++;
}

// index is 24
System.out.print(index);

【讨论】:

    【解决方案2】:
     public static int findIndex(String string, char c, int n)
     {
        int len = string.length();
        return IntStream.range(0, len)
                .filter(i -> c == string.charAt(i))
                .skip(n-1)
                .findFirst() 
                .orElse(-1); // No element found
     }
    

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 2016-11-21
      • 2020-02-26
      • 1970-01-01
      • 2021-04-07
      相关资源
      最近更新 更多