Home > database >  (Java) How can I count the number of tab and space before the first character of a string
(Java) How can I count the number of tab and space before the first character of a string

Time:08-05

(Java) How can I count the number of tab and space before the first character of a string

Assume that a string String line = " Java is good."

There are totally 10 spaces in this string. However, how can I count the number of tab and space before the first character "J" only? There are 8 spaces before the first character "J" only.

CodePudding user response:

How about:

    String s = "        Java is good.";
    int total = 0;
    for (int i = 0; i < s.length(); i  ) {
      if (Character.isWhitespace(s.charAt(i))) {
        total  ;
      } else {
        break;
      }
    }
    System.out.println(total);

Or

    String s = "        Java is good.";
    int total = 0;
    for (int i = 0; i < s.length(); i  ) {
      char ch = s.charAt(i);
      if (ch == ' ' || ch == '\t') {
        total  ;
      } else {
        break;
      }
    }
    System.out.println(total);

CodePudding user response:

We can use a regex replacement length trick here:

String line = "\t   \t  Java is good.";
int numSpaces = line.length() - line.replaceAll("^[\t ] ", "").length();
System.out.println(numSpaces);  // 7

CodePudding user response:

For a project which uses the Guava library, the CharMatcher class can determine this:

int count = CharMatcher.noneOf(" \t").indexIn(line);

If the string does not contain a non-space, non-tab character, -1 is returned. Depending on the desired behavior, this special value can be checked for and an appropriate value returned.

CodePudding user response:

For a project which uses the StreamEx library, the IntStreamEx.indexOf() method can determine this:

long count = IntStreamEx.ofChars(line).indexOf(c -> c != ' ' && c != '\t')
        .orElse(line.length());

If the string does not contain a non-space, non-tab character, the length of the string is returned. This behavior can be changed by returning a different value from .orElse or otherwise changing how the OptionalLong value is accessed.

CodePudding user response:

There is a trim method which removes leading and trailing whitespaces. If you were positive there was only leading whitespace and not trailing, you could compare the length of the non-trimmed with the trimmed.

`

int diff = line.length - line.trim().length;

`

Or just count with a for loop

`

int spaces = 0;
for(int x = 0; x < line.length; x  ){
    if(line[x].equals(" ")){
        spaces  ;
    }else break;
}

`

  •  Tags:  
  • java
  • Related