ChosenForWorlds
ChosenForWorlds

Reputation: 95

Replace tab with blank space

final String remove = "   " // tab is 3 spaces

while (lineOfText != null)
   {
       if (lineOfText.contains(remove))
       {
           lineOfText = " ";
        }
       outputFile.println(lineOfText);
       lineOfText = inputFile.readLine();
   }

I tried running this but it doesn't replace the tabs with one blank space. Any solutions?

Upvotes: 6

Views: 32052

Answers (2)

Daniel Plaku
Daniel Plaku

Reputation: 61

You can simply use this regular expression to replace any type of escapes( including tabs, newlines, spaces etc.) within a String with the desired one:

lineOfText.replaceAll("\\s", " ");

Here in this example in the string named lineOfText we have replaced all escapes with whitespaces.

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201467

Tab is not three spaces. It's a special character that you obtain with an escape, specifically final String remove = "\t"; and

if (lineOfText.contains(remove))
    lineOfText = lineOfText.replaceAll(remove, " ");
}

or remove the if (because replaceAll doesn't need it) like,

lineOfText = lineOfText.replaceAll(remove, " ");

Upvotes: 12

Related Questions