The Wayback Machine - https://web.archive.org/web/20240717024726/https://www.geeksforgeeks.org/python-remove-leading-zeros-ip-address/
Open In App

Python | C++ | Remove leading zeros from an IP address

Last Updated : 27 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given an IP address, remove leading zeros from the IP address.

Examples:  

Input : 100.020.003.400 
Output : 100.20.3.400

Input :001.200.001.004  
Output : 1.200.1.4

The approach is to split the given string by “.” and then convert it to an integer which removes the leading zeros and then join back them to a string.To convert a string to an integer we can use int(s) and then convert it back to string by str(s) and then join them back by using join function.

Implementation:

C++




// Cpp program to remove leading zeros
// an IP address and print the IP
  
#include <bits/stdc++.h>
using namespace std;
  
// function to remove leading zeros
string removeZeros(string s)
{
    vector<string> v;
  
    // splits the ip by "."
    for (int i = 0; i < s.length(); i++) {
        string ans;
        while (i < s.length() && s[i] != '.') {
            ans += s[i];
            i++;
        }
        v.push_back(ans);
    }
  
    vector<int> num;
    // converts the words to integers to remove leading removeZeros
    for (auto str : v) {
        int temp = 0;
        for (int i = 0; i < str.length(); i++) {
            temp *= 10;
            temp += (str[i] - '0');
        }
        num.push_back(temp);
    }
  
    string ans = "";
    // Convert back the integer to string and join them back to a string
    for (auto i : num) {
        ans += '.';
        string temp;
        while (i) {
            temp += ('0' + (i % 10));
            i /= 10;
        }
        reverse(temp.begin(), temp.end());
        ans += temp;
    }
  
    return ans.substr(1);
}
  
int main()
{
    string ip;
    // example1
    ip = "100.020.003.400";
    cout << (removeZeros(ip)) << "\n";
    // example2
    ip = "001.200.001.004";
    cout << (removeZeros(ip)) << "\n";
    return 0;
}


Python




# Python program to remove leading zeros
# an IP address and print the IP
  
# function to remove leading zeros
def removeZeros(ip):
      
    # splits the ip by "."
    # converts the words to integers to remove leading removeZeros
    # convert back the integer to string and join them back to a string
    new_ip = ".".join([str(int(i)) for i in ip.split(".")])
    return new_ip ;
      
      
# driver code 
# example1
ip ="100.020.003.400"
print(removeZeros(ip))
  
  
# example2
ip ="001.200.001.004"
print(removeZeros(ip))


Output

100.20.3.400
1.200.1.4

Method 2 : Regex

Using a capture group, match the last digit and copy it and prevents all the digits from being replaced. 
regex \d can be explained as: 

  • \d : Matches any decimal digit
\d   Matches any decimal digit, this is equivalent
     to the set class [0-9].
  • \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b 
    regex \b can be explained as:
\b allows you to perform a "whole words only" search u
sing a regular expression in the form of \bword\b

Implementation:

Python




# Python program to remove leading zeros
# an IP address and print the IP using regex
import re
 
# function to remove leading zeros
def removeZeros(ip):
    new_ip = re.sub(r'\b0+(\d)', r'\1', ip)
    # splits the ip by "."
    # converts the words to integers to remove leading removeZeros
    # convert back the integer to string and join them back to a string
     
    return new_ip
     
     
# driver code
# example1
ip ="100.020.003.400"
print(removeZeros(ip))
 
 
# example2
ip ="001.200.001.004"
print(removeZeros(ip))


Output

100.20.3.400
1.200.1.4

Method 3: Storing the index of the first non zero character.

The approach is to split the string by “.” and store it in another string x.

Now get the index of the first non-zero character of that string and store

it in another variable ind. Initialise that variable to -1 which indicates that there is

no non-zero character in the string .In another variable append the substring picking

up characters from that index till the end in another string y.

Source code : c++ solution

C++




#include<bits/stdc++.h>
using namespace std;
int main()
{
   string s="152.02.0015.00";
   string newIPAdd(string);
   cout<<newIPAdd(s);
   return 0;
}
string newIPAdd (string s)
   {
       long long int i,l,f=0,ind=-1;// initialising ind to -1 to indicate that there is no non-zero character in the string
       string x="",y="";
       char c;
       s=s+".";
       l=s.length();
       for(i=0;i<l;i++)
       {
           c=s.at(i);
           if(c!='.')
           {
               x=x+c;
               if(c!='0' && f==0)
               {
                   ind=x.length()-1;// getting the index of first non-zero character
                   f=1;//flag=1 to prevent further change of index for another non-zero character
               }
 
           }
           else
           {
                 
               if(ind==-1)
               y=y+"."+"0";
               else
               y=y+"."+x.substr(ind);//appending it to the another string
               ind=-1;f=0;x="";
           }
       }
       return y.substr(1);
   }


Output

152.2.15.0


Similar Reads

Why is the IP address called a "logical" address, and the MAC address is called a "physical" address?
Let us try to deeply understand, why IP address is known as "Logical" while, MAC Address is known as "Physical" address. The IP address and the MAC address are both used for addressing and identifying devices on a computer network, but they serve different purposes and operate at different levels of the network stack. An IP address is a logical add
7 min read
IP address as logical address and MAC address as Physical address
Overview :IP addresses and MAC addresses are essential for data communication. Assume there are two networks. The first network has three devices: A, B, C and the second network has three devices: X, Y, Z. If a device A from the first network wishes to send data to a device Y in the second network, it must first determine where Y is located in the
6 min read
Remove leading zeros from an array
Given an array of N numbers, the task is to remove all leading zeros from the array. Examples: Input : arr[] = {0, 0, 0, 1, 2, 3} Output : 1 2 3 Input : arr[] = {0, 0, 0, 1, 0, 2, 3} Output : 1 0 2 3 Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the arra
7 min read
Remove leading zeros from a Number given as a string
Given numeric string str, the task is to remove all the leading zeros from a given string. If the string contains only zeros, then print a single "0". Examples: Input: str = "0001234" Output: 1234 Explanation: Removal of leading substring "000" modifies the string to "1234". Hence, the final answer is "1234". Input: str = "00000000" Output: 0 Expla
7 min read
How to Add leading Zeros to a Number in Python
In this article, we will learn how to pad or add leading zeroes to the output in Python. Example:Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).Display a Number With Leading Zeros in PythonAdd leading Zeros to numbers using format() For more effective handling of sophisticated string formatting, Python has included the for
3 min read
All possible numbers of N digits and base B without leading zeros
Given a number of digits 'N' and base 'B', the task is to count all the 'N' digit numbers without leading zeros that are in base 'B' Examples: Input: N = 2, B = 2 Output: 2 All possible numbers without leading zeros are 10 and 11. Input: N = 5, B = 8 Output: 28672 Approach: If the base is 'B' then every digit of the number can take any value within
4 min read
Number of leading zeros in binary representation of a given number
Given a positive integer N, the task is to find the number of leading zeros in its binary representation.A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form. Examples: Input : N = 16Output : 27Explanation: As Binary(16) = (00000000000000000000000000010000) Input : N = 33Output : 26Explanation: As Binary
10 min read
Count numbers having N 0's and M 1's with no leading zeros
Given two integer N and M, the task is to find the number of distinct numbers having N 0's and M 1's with no leading zeros and N + M total digits. Examples: Input: N = 2, M = 2 Output: 3 The numbers are 1001, 1010 and 1100. Input: N = 2, M = 3 Output: 6 The numbers are 10011, 10101, 10110, 11001, 11010 and 11100. Approach: The problem can be easily
5 min read
Count of N-bit binary numbers without leading zeros
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples: Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8 Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now for the rest of the N - 1 bits, there are two choice
2 min read
Check if any permutation of a number without any leading zeros is a power of 2 or not
Given an integer N, the task is to check if any permutation of N without any leading zeros is a power of 2. If any such permutation of the given number exists, then print that permutation. Otherwise, print No. Examples: Input: N = 46Output: 64Explanation:The permutation of 46 which is perfect power of 2 is 64( = 26) Input: N = 75Output: NoExplanati
9 min read
three90RightbarBannerImg