Microsoft Interview Question
Country: United States
The below line should be
string[] numbers = inputString.split("\\.");
Else can use the:
StringTokenizer stringTokenizer = new StringTokenizer( ip, "." );
while ( stringTokenizer.hasMoreTokens() ) {
byte byteValue = Byte.parseByte(stringTokenizer.nextToken()) ;
}
public static bool IsValidIp(string address)
{
int dotCount = 0;
int returnValue = 0;
var isValid = true;
var total = 0;
foreach (var digit in address)
{
if ((digit < '0' || digit > '9') && digit != '.' || !isValid)
return false;
if (digit == '.')
{
total += returnValue;
returnValue = 0;
dotCount++;
continue;
}
returnValue = (returnValue * 10) + (digit - '0');
isValid &= returnValue < 256;
}
isValid &= (total != 0) && (total <= (255 * 4)) && dotCount == 3;
return isValid;
}
Using the inet_pton - which returns -1 on failure, and supports both the IPv4 and future IPv6 addresses
#include <arpa/inet.h>
bool isValidIP(char * ipAddr)
{
struct sockaddr_in socAddr;
return ( inet_pton(AF_INET, ipAddr, &(socAddr.sin_addr)) != 0 ) ;
}
Using Regular Expressions for IPV4:
package sample;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPAddrValidator {
public boolean validate(final String ip){
matcher = pattern.matcher(ip);
return matcher.matches();
}
public IPAddrValidator() {
pattern = Pattern.compile(IP_ADDRESS_PATTERN);
}
private Pattern pattern;
private Matcher matcher;
private static final String IP_ADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
public static void main(String[] args) {
// TODO Auto-generated method stub
String ip = new String ("1.1.1.1") ;
IPAddrValidator ipValidator = new IPAddrValidator();
System.out.println("IP Address = "+ ip + " is " + ipValidator.validate(ip) );
System.out.println("IP Address = "+ "127.0.0.1" + " is " + ipValidator.validate("127.0.0.1") );
System.out.println("IP Address = "+ "10.10" + " is " + ipValidator.validate("10.10") );
}
}
String IP="129.777.0.0";
boolean isValid=true;
String ip[]=IP.split("\\.");
if(ip.length>4)
isValid=false;
else
{
for(int i=0;i<ip.length;i++)
{
try
{
int n=Integer.parseInt(ip[i]);
if(n<0||n>255)
{
isValid=false;
break;
}
}
catch(NumberFormatException e)
{
isValid=false;
}
}
if(isValid)
System.out.println("valid IP");
else
System.out.println("Inavalid IP");
}
String ip="129.1.0.0";
boolean isValid=true;
String ipa[]=new String[4];
//max size of ip is 15
if(ip.length()>15)
isValid=false;
else
{
int i=ip.indexOf('.');
int j=ip.lastIndexOf('.');
ipa[0]=ip.substring(0,i);
ipa[3]=ip.substring(j+1,ip.length());
String mid=ip.substring(i+1,j);
ipa[1]=mid.substring(0,mid.indexOf('.'));
ipa[2]=mid.substring(mid.indexOf('.')+1,mid.length());
for(i=0;i<4;i++)
{
try
{
int n=Integer.parseInt(ipa[i]);
if(n<0||n>255)
{
isValid=false;
break;
}
}
catch(NumberFormatException e)
{
isValid=false;
}
}
}
if(isValid)
System.out.println("valid IP");
else
System.out.println("Inavalid IP");
In C++:
bool isValidIp(const std::string &ip)
{
int dotidx[3];
int idx, len = ip.length();
int currdot = 0;
for (idx = 0; idx < len; ++idx) {
if (ip[idx] == '.') {
// string has more than 3 dots
if (currdot > 2) {
return false;
}
dotidx[currdot] = idx+1;
++currdot;
}
else if (ip[idx] < '0' or ip[idx] > '9') {
// non numeric
return false;
}
}
// less than 3 dots
if (currdot != 3)
return false;
int i;
// empty bytes
for (i = 0; i < 2; ++i) {
if (dotidx[i]+1 == dotidx[i+1]) {
return false;
}
}
if (dotidx[2] >= len) {
return false;
}
for (i = 0; i < 3; ++i) {
std::string byte;
if (i < 2) {
byte = ip.substr(dotidx[i], dotidx[i+1]-dotidx[i]-1);
}
else {
byte = ip.substr(dotidx[i], len-dotidx[i]);
}
int decimal = atoi(byte.c_str());
if (decimal > 255) {
return false;
}
}
return true;
}
I assume that making use of regular expressions, Socket API and system parse methods is a bit of overhead. At least, it's not what interviewers usually expect. Here's the code that gets the job done with one simple linear scan.
namespace CareerCup
{
public class ValidIpAddress
{
public bool IsValidIpAddress(string input)
{
if (string.IsNullOrEmpty(input) || input.Length > 15)
{
return false;
}
int lastOctet = 0;
bool hasLeadingZeros = false;
int octetsCount = 0;
for (int i = 0; i < input.Length; ++i)
{
bool checkLastOctet = false;
char current = input[i];
if (char.IsDigit(current))
{
lastOctet = lastOctet * 10 + (input[i] - '0');
if (lastOctet == 0)
{
hasLeadingZeros = true;
}
if (i == input.Length - 1)
{
checkLastOctet = true;
}
}
else if (current == '.')
{
checkLastOctet = true;
}
else
{
return false;
}
if (checkLastOctet)
{
if (lastOctet > 255 || (lastOctet != 0 && hasLeadingZeros))
{
return false;
}
lastOctet = 0;
hasLeadingZeros = false;
octetsCount++;
}
}
return octetsCount == 4;
}
}
}
public static boolean isValidIP(String s) {
String[] _ipArray = s.split("\\.");
if (_ipArray.length != 4)
return false;
else {
for (String string : _ipArray) {
try{
if (!(Integer.parseInt(string) >= 0 || Integer.parseInt(string) <= 255))
return false;
}
catch(NumberFormatException e){
return false;
}
}
}
return true;
}
public static bool IsValidIp(string address)
{
int dotCount = 0;
int returnValue = 0;
var isValid = true;
var total = 0;
foreach (var digit in address)
{
if ((digit < '0' || digit > '9') && digit != '.' || !isValid)
return false;
if (digit == '.')
{
total += returnValue;
returnValue = 0;
dotCount++;
continue;
}
returnValue = (returnValue * 10) + (digit - '0');
isValid &= returnValue < 256;
}
isValid &= (total != 0) && (total <= (255 * 4)) && dotCount == 3;
return isValid;
}
public static boolean isValidIp(String s){
if(s==null || s.length()==0||s.length()>15) return false;
for(int i = 0,num=0,numDots=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='.'){
if(++numDots>3 || num>255) return false;
num = 0;
}else{
int digit = c-'0';
if(digit<0||digit>9)return false;
num*=10;
num+=digit;
if(num>255)return false;
}
}
return true;
}
#include <iostream>
#include <string.h>
using namespace std;
bool isValid(const char *str) {
int len = strlen(str);
bool valid = true;
int numCount = 0, dotCount = 0;
for(int i = 0; i < len;) {
int j = i;
int num = 0;
if(numCount == 4) {
valid = false;
break;
}
for(; j < len; ++j) {
if(str[j] < '0' || str[j] > '9')
break;
num = num * 10 + (str[j] - '0');
}
if((j == i) || (num < 0) || (num > 255)) {
valid = false;
break;
}
numCount++;
if(j < len) {
if((str[j] != '.') || ((str[j] == '.') && (dotCount == 3))) {
valid = false;
break;
}
else
dotCount++;
j++;
}
i = j;
}
if((numCount != 4) && (dotCount != 3))
valid = false;
return valid;
}
int main() {
cout << boolalpha << isValid("255...") << endl;
cout << boolalpha << isValid("255.255.255. 255") << endl;
cout << boolalpha << isValid(".") << endl;
cout << boolalpha << isValid(".255.255.t") << endl;
return 0;
}
this function only does validation on IP4 addresses
- akiremi January 23, 2015