-1

I am trying to do a String.split on a website address using the "." so that I can find the domain name of the website.

However, when I do this:

String href = "www.google.com";
String split[] = href.split(".");
int splitLength = split.length;

It tells me that the splitLength variable is 0. Why is this, and how can I make this work?

Roman C
  • 49,761
  • 33
  • 66
  • 176
shieldgenerator7
  • 1,507
  • 17
  • 22

2 Answers2

4

Split uses a regex so do:

String split[] = href.split("\\.");
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Jason
  • 13,563
  • 15
  • 74
  • 125
4

Try using this to split the string:

href.split("\\.");

Explanation: split splits on a regex, not on a regular substring. In regexes, . is the metacharacter for 'match any character', which we don't want. So we have to escape it using a backslash \. But \ is also a metacharacter for escaping in Java strings, so we need to escape it twice.

Patashu
  • 21,443
  • 3
  • 45
  • 53
Sameer Anand
  • 274
  • 2
  • 13