0

I am trying to split a String by . :

String sentences[] = fileContent.split(".");

fileContent is a string that contains the complete text data from a file. In the file there are 4 sentences some separated by white space gaps.

When I print sentences[n] it gives a blank . Why is it so when sentences.length prints 95.

Data structured in fileContent looks like : (no-meaning text)

My name is suhail. His name is suhail.

He was playing with suhail. He is cool and loves suhail.
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

3

You have to escape the dot character, because split() expects a regex (regular expression), not a plain string:

String sentences[] = fileContent.split("\\.");
keyser
  • 18,829
  • 16
  • 59
  • 101
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • To get a token out of `Rose is a flower`, will I put it like : `split("\\ ")` ? – Suhail Gupta Apr 05 '14 at 20:37
  • No. You have to scape the dot, because it represents a *special character* in regex. If you want to split by a single space, use `split(" ")`. If you want to split by *any whitespace* you can use `split("\\s+")`. I will recommend you to read about regex so you understand how to use it. – Christian Tapia Apr 05 '14 at 20:39
  • It'd be worth mentioning that a dot has special meaning in RegEx -- which is why it needs to be escaped -- while a space does not have special meaning -- which is why it doesn't need to be escaped. – Mihai Stancu Apr 05 '14 at 20:53