john
john

Reputation: 11699

What is the best way to check whether a particular string is present in a hostname or not?

I have a hostname like this p-desktop-1234565.teck.host.com which I need to check whether it is in teck domain/datacenter or not. Any hostname will be in teck domain, if it has .teck. in the hostname.

As an example we might have machine in other datacenters (dc1, dc2, dc3) so there hostname will be like this -

machineA.dc1.host.com
machineB.dc2.host.com
machineC.dc3.host.com

In the same way might have some machine in teck domain so we might have hostname like this -

machineD.teck.host.com

So I need to check whether any machine is in teck datacenter or not. So I have got the below code which works fine -

String hostname = getHostName();

if (hostname != null) {
    if (isTeckHost(hostname)) {
        // do something
    }
}

// does this look right or is there any other better way?
private static boolean isTeckHost(String hostName) {
    return hostName.indexOf("." + TECK.name().toLowerCase() + ".") >= 0;
}

I wanted to check whether indexOf is the right way to use here? Or is there any better or efficient way to do the same thing?

Note: This piece of code is in my Enum class in which TECK is declared.

Upvotes: 1

Views: 666

Answers (2)

Dermot Blair
Dermot Blair

Reputation: 1620

Use String's contains() method if you just need to check if a string contains another string. For example:

if(hostName.toLowerCase().contains("." + TECK.name().toLowerCase() + "."))

Use String's split method if you need to check if a string is in a certain place in the hostname (e.g. before the first period, before the second period, etc.). For example:

if(hostName.toLowerCase().split("\\.")[1].equals(TECK.name().toLowerCase()))

split() returns a string array that contains the substrings in the string it is called on that are divided by a certain regex pattern, in this case, a full stop.

For example, when split("\\.") is called on the string p-desktop-1234565.teck.host.com, it will return the following array: {"p-desktop-1234565", "teck", "host", "com"}. We then check (using [1]) if the second item in the array is equal to "teck".

Upvotes: 2

Aify
Aify

Reputation: 3537

While the contains method is generally safe to use, for a purpose such as this I recommend a combination of split() and .equals()

eg:

String[] x = hostname.split("\."); // this splits the string, and since the host is always in the second spot, you can do the following
if (x[1].equals(TECK.name().toLowerCase())) { 
    // do your stuff 
}

This one is safer in the sense that I can't break it with a string like machineE.dc4.teck.com (assuming that this isn't allowed)

Upvotes: 1

Related Questions