Home > Enterprise >  Reverse order of string, but keep numbers intact
Reverse order of string, but keep numbers intact

Time:02-03

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.

CodePudding user response:

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.

CodePudding user response:

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);
}
  •  Tags:  
  • Related