-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
  • 48,723
  • 33
  • 63
  • 158
shieldgenerator7
  • 1,267
  • 16
  • 22

2 Answers2

4

Split uses a regex so do:

String split[] = href.split("\\.");
Paul Bellora
  • 53,024
  • 17
  • 128
  • 180
Jason
  • 12,288
  • 14
  • 67
  • 121
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
  • 20,895
  • 3
  • 42
  • 52
Sameer Anand
  • 264
  • 2
  • 12