给定IP地址,从IP地址中删除前导零。 例如:
null
Input : 100.020.003.400 Output : 100.20.3.400Input :001.200.001.004 Output : 1.200.1.4
方法1:遍历和连接
这个 方法 将给定字符串拆分为“”然后把它转换成一个整数,去掉前导零,然后把它们连接回一个字符串。要将字符串转换为整数,我们可以使用 int(s) 然后通过 str(s) 然后使用join函数将它们重新连接起来。
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 integeres 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)) |
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 integeres 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)) << "" ; // example2 ip = "001.200.001.004" ; cout << (removeZeros(ip)) << "" ; return 0; } |
输出:
100.20.3.4001.200.1.4
方法2: 正则表达式
使用捕获组,匹配最后一个数字并复制它,防止所有数字被替换。 正则表达式d 可以解释为:
- d: 匹配任何十进制数字
d Matches any decimal digit, this is equivalent to the set class [0-9].
- 允许您使用word格式的正则表达式执行“仅限整词”搜索 regex可以解释为:
allows you to perform a "whole words only" search using a regular expression in the form of word
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 '0+(d)' , r '1' , ip) # splits the ip by "." # converts the words to integeres 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)) |
输出:
100.20.3.4001.200.1.4
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END