midoriyakuzan
midoriyakuzan

Reputation: 23

Reverse order of string, but keep numbers intact

I have a string like this:

1.1.168.192

I need to convert it to this, with the numbers intact but the order reversed:

192.168.1.1

This seems like an easy question, but I cant figure it out. I'm trying something within a for loop right now but I don't know how to make it work.

Upvotes: 0

Views: 556

Answers (2)

Wolfimschafspelz
Wolfimschafspelz

Reputation: 316

you could split your your string and reverse this array and join it together like this:

string reverseIP(string ip) { // ip = "1.1.168.192"
    string[] ipParts = ip.split('.'); // ["1", "1", "168", "192"]
    Array.Reverse(ipParts);
    
    return String.Join(".", ipParts);
}

Upvotes: 0

ibrahim-dogan
ibrahim-dogan

Reputation: 621

This could help:

string[] splitted = "1.1.168.192".Split('.');
Array.Reverse(splitted);
string reversed = string.Join(".", splitted);

The idea is you can split things by using a char and it creates an array, then reverse it, and then join them by using a char again it will become string again.

Upvotes: 1

Related Questions