views:

258

answers:

1

Hi

How would I parse a domain name in objective -c?

For example if my string value was "http://www.google.com" I would like to parse out the string "google"

+2  A: 

I think the question is a tiny bit invalid. A host is determined by its FQDN (fully qualified domain name) which, in your example, is www.google.com. It's not the same as mail.google.com or www.google.info or google.com. To single out "google" is not trivial and does not make much sense from URL perspective.

If you'd like to just parse the URL more-or-less intelligently, I think you can do the following:

  1. Use NSURL's -host method to get the scheme and path/query stripped correctly.
  2. Use NSString's -componentsSeparatedByString: method to get an array of the domain name's "components".
  3. Ignore the last component.
  4. If there's only one component left (or it may be enough to take the second-last component), you're done.
  5. If the first component contains "www" like www3, "ftp", "mail" or something of their kind, you can ignore it too if you like. The rest may be of interest, depending on your needs.
  6. Test your algorithm against ten thousand URLs to get a sense of futility of this task ;)
Costique
dubbeat