-6

Hi everybody I writing java code which counts characters. When I convert String using toCharArray I cant use regex to eliminate whitespaces.

    System.out.println( "Enter a string:" ); 
    String input = scanner.nextLine();

    // tokenize the input
    char[] chars = input.toCharArray();
arsen
  • 23
  • 1
  • 3
  • 1
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. – Yassin Hajaj Apr 05 '16 at 13:23
  • 1
    Are you trying to convert your string to a char array, or just to count some characters (which certainly doesn't require you to convert to a char array)? – khelwood Apr 05 '16 at 13:24

1 Answers1

9

This:

input.replaceAll(" ", "").toCharArray()

Probably better to use length() to count the chars though...

dambros
  • 4,252
  • 1
  • 23
  • 39
  • 5
    Any reason to use `replaceAll` instead of `replace`? – Tom Apr 05 '16 at 13:26
  • If there is more than just a single whitespace – PendingValue Apr 05 '16 at 13:29
  • 2
    @PierrePascalLindenberg You should read the JavaDoc of both methods ;). – Tom Apr 05 '16 at 13:30
  • @Tom I always end up using `replaceAll` due to habit, but you are correct if we take speed into consideration. `replace` would be faster since it does not have to compile a regex. – dambros Apr 05 '16 at 13:34
  • 1
    Well, I don't know if `replace` is faster than `replaceAll`, but it tends to be error prone to use `replaceAll` if one doesn't know that this expects a regular expression and doesn't escape certain chars correctly (happens quite often with newbies :D). – Tom Apr 05 '16 at 13:39
  • @PierrePascalLindenberg The method names are quite inappropriate since the `All` in `replaceAll` tends to say "I replace all, whereas `replace` replaces only the first find". `replaceRegex` would be a bit better, but this won't be ever changed :D. – Tom Apr 05 '16 at 13:44
  • @Tom haven't though about this aspect of the "problem". You are completly right regarding newbies. – dambros Apr 05 '16 at 13:45