Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace tab with blank space

Tags:

java

tabs

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?

like image 565
ChosenForWorlds Avatar asked Dec 24 '22 22:12

ChosenForWorlds


2 Answers

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, " ");
like image 112
Elliott Frisch Avatar answered Dec 26 '22 10:12

Elliott Frisch


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.

like image 30
Daniel Plaku Avatar answered Dec 26 '22 11:12

Daniel Plaku