有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java字符串中查找给定字符之前的最后一个字符

假设我有以下字符串:

String string = "122045b5423";

在Java中,找到b之前的最后2个最有效的方法是什么? 我知道我可以拆分字符串,然后从string类中使用lastIndexOf()方法,但是 有没有一种更有效的方法可以减少变量的创建。StringBuilder类中是否有允许我们执行此操作的方法


共 (3) 个答案

  1. # 1 楼答案

    请看String类(或subSequence)的方法substring。那会给你你需要的

    代码应该是这样的

    String result = null;
    int index = myString.indexOf("b");
    if(index > -1) {
      if(index >= 2) {
        result = myString.substring(index - 2, index);
      } else {
        result = myString.substring(0, index);
      }
    }
    
  2. # 2 楼答案

    我认为最简单的方法(几乎没有内存开销)是自己扫描字符串:

    int findLastCharBeforeChar(final String string, final char anchor, final char needle) {
      int i = string.length() - 1;
      while (i >= 0 && string.charAt(i) != anchor) {
         i;
      }
      while (i >= 0) {
        if (string.charAt(i) == needle) return i;
         i;
      }
      return i;
    }
    

    如果您想让它稍微短一点(但可能会稍微慢一点,而且肯定更难阅读):

    int findLastCharBeforeChar(final String string, final char anchor, final char needle) {
      char target = anchor;
      while (i >= 0) {
        final char ch = string.charAt(i);
        if (ch == target) target = needle;
        if (target == needle && ch == target) return i;
         i;
      }
      return i;
    }
    

    不是问了什么(效率最高),而是在“最短”解决方案的评论中进行了跟进(请注意,这远不是有效的,取决于您称之为“最短”解决方案的地方,这可能是不好的):

    string.split('b')[0].lastIndexOf('2');
    

    如果'b'不是输入字符串的一部分,您没有在OP中指定应该发生什么。结果应该是-1吗?(将与我的第一个实现一起使用)或者该方法应该只返回字符串中最后一个'2'的索引(字符串拆分解决方案)?更改方法以处理这种情况也很简单,只需检查第一个循环是否在-1终止,并将索引重置为字符串的最后一个索引

    但这有点没有实际意义。将9行代码放入一个方法中,为其编写适当的单元测试,然后调用新方法。调用新方法是:a)一行程序b)高效c)可能由JVM内联

  3. # 3 楼答案

    如果您正在寻找一个更紧凑的解决方案,那么regex呢

    // A 2, followed by arbitrary chars that are not a 2 and finally a b
    Pattern pattern = Pattern.compile("(2)[^2]*b");
    Matcher matcher = pattern.matcher(string);
    
    if (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end());
        System.out.println(" Found: " + matcher.group());
    }
    

    我还没有测试过它,但类似的东西应该可以工作