0

I am using this code to read a txt file, line by line.

// Open the file that is the first command line parameter 
FileInputStream fstream = new FileInputStream("/Users/dimitramicha/Desktop/SweetHome3D1.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
int i = 0;
while ((strLine = br.readLine()) != null) {
    str[i] = strLine;
    i++;
}
// Close the input stream
in.close();

and I save it in an array.

Afterwards, I would like to make an if statement about the Strings that I saved in the array. But when I do that it doesn't work, because (as I've thought) it saves also the spaces (backslashes). Do you have any idea how I can save the data in the array but without spaces?

ring bearer
  • 20,383
  • 7
  • 59
  • 72
Mitsaki
  • 11
  • 2
  • 6

3 Answers3

1

I would do:

strLineWithoutSpaces = strLine.replace(' ', '');
str[i] = strLineWithoutSpaces;

You can also do more replaces if you find other characters that you don't want.

Dan W
  • 5,718
  • 4
  • 33
  • 44
  • Well I tried String strLineWithoutSpaces = strLine.replace(" ",""); str[i] = strLineWithoutSpaces; but it is not right yet... – Mitsaki Aug 22 '11 at 20:11
  • After looking into this more, I found this works: strLine.replaceAll("\\s+", ""); If you want more in depth deletion of white space (not always middle), check out this link: http://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-leadi – Dan W Aug 22 '11 at 20:34
  • Still, all the blanks are not gone... I also used replaceAll("^ +| +$|( )+", "$1") as the other post suggests. – Mitsaki Aug 22 '11 at 21:13
  • What if I just want to replace \n ? – Mitsaki Aug 22 '11 at 21:38
  • Try: strLine.replaceAll("\n", ""); ReplaceAll takes a Regex and you can read more about them: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum – Dan W Aug 22 '11 at 21:45
0

Have a look at the replace method in String and call it on strLine before putting it in the array.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0

You can use a Scanner which by default uses white space to separate tokens. Have a look at this tutorial.

dimitrisli
  • 20,895
  • 12
  • 59
  • 63