2017-09-15 82 views
-4

在java中,我将如何找到第一个空白字符后第一个非空白字符的索引?例如,假设我有串:如何获得字符串中第一个非空白字符的索引?

String mystring = "one two three" 

我想某种方法将返回值:4 由于字符“T”是第一个空格后的第一个字符。

+0

你会在单词之间有多个空格吗?这会稍微改变问题的解决方案。 –

+0

你会写一些代码来做到这一点。 –

回答

1

这似乎是工作,并且输出4

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()); 
    } 
} 
0

有这个没有内置功能。然而,编写一个这样的函数是相当简单的:

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; 
} 
相关问题