代码之家  ›  专栏  ›  技术社区  ›  GregH

如何获取字符串中第一个非空白字符的索引?

  •  -2
  • GregH  · 技术社区  · 7 年前

    String mystring = "one two three"
    

    我想要某种返回值的方法:4 因为字符“t”位于第一个空格后的第一个字符中。

    2 回复  |  直到 7 年前
        1
  •  1
  •   jrtapsell    7 年前

    public class Example {
      public static void main(final String... args) {
        Pattern p = Pattern.compile("([^\\s]+)?(\\s)+");
        String mystring = "one two three";
        final Matcher matcher = p.matcher(mystring);
        matcher.find();
        System.out.println(matcher.end());
      }
    }
    
        2
  •  0
  •   Infuzion Stu Thompson    7 年前

    没有用于此的内置函数。然而,编写一个函数来实现这一点非常简单:

    public static int getIndexOfNonWhitespaceAfterWhitespace(String string){
        char[] characters = string.toCharArray();
        boolean lastWhitespace = false;
        for(int i = 0; i < string.length(); i++){
            if(Character.isWhitespace(characters[i])){
                lastWhitespace = true;
            } else if(lastWhitespace){
                return i;
            }
        }
        return -1;
    }