-4

I am trying to remove whitespaces in the beginning of my String by doing the .trim() method. But when I try to calculate how many whitespaces I remove it won't work. I have tried making an equation: int spaces = line.length() - line.trim().length(). But for some reason it always ends up saying the length of the line thats being inputted. Am I missing something here? Or is it some other part of my code?

public Squeeze(FileInput inFile, FileOutput outFile)
{
    int spaces = 0;
    String line = "";
    while(inFile.hasMoreLines())
    {
        line = inFile.readLine();
        line = line.trim();
        spaces = line.length() - line.trim().length();
        outFile.println(spaces + line);

    }
    outFile.close();
}

1 Answers1

1

Note: The OP's code doesn't actually count all whitespaces, only leading ones. For those who want a direct answer to the question:

If you have commons:

int count = StringUtils.countMatches(yourText, " ");

If you don't:

int count = yourText.length() - yourText.replace(" ", "").length();

The following solution is based on the OP's code only.

Your problem is in this part:

line = line.trim();
// At this point, 'line' has already been trimmed.
spaces = line.length() - line.trim().length();

You'll need to either put the trimmed version into some other variable, or move the line = line.trim() line until at least after you've counted the spaces.

public Squeeze(FileInput inFile, FileOutput outFile)
{
int spaces = 0;
String line = "";
String trimmedLine = "";
while(inFile.hasMoreLines())
{
    line = inFile.readLine();
    trimmedLine = line.trim();
    spaces = line.length() - trimmedLine.length();
    outFile.println(Format.left(spaces, 4) + line);

}
outFile.close();
}
Luke Briggs
  • 3,745
  • 1
  • 14
  • 26
  • 1
    Ha! I suspected this was the problem until OP posted his conveniently trimmed-down code. – shmosel Nov 15 '16 at 04:15
  • Wouldn't this mean their output would always be `0`? How did they get `11`? – 4castle Nov 15 '16 at 04:17
  • We must still missing some of the code (thus the downvotes) - I took the assumption that the 'spaces' line is probably different, but the underlying issue is probably related to this. – Luke Briggs Nov 15 '16 at 04:20