xyz xyz Interview Question
XYZs XYZsTeam: XYZ
Country: XYZ
Sample parsing in Java:
import java.io.*;
import java.util.*;
public class EmployeeParse {
private Integer empID ;
private String empName ;
private String empCity ;
public Integer getEmpID() {
return empID;
}
public void setEmpID(Integer empID) {
this.empID = empID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpCity() {
return empCity;
}
public void setEmpCity(String empCity) {
this.empCity = empCity;
}
public EmployeeParse() {
}
public static void main(String[] args) {
try {
ArrayList<EmployeeParse> empList = new ArrayList<EmployeeParse>() ;
File file = new File ( "/Users/ramesh/Documents/workspace/Programs/src/employee.rtf") ;
if ( file.exists() )
{
Scanner inFile = new Scanner( file );
inFile.useDelimiter("[;]");
while ( inFile.hasNext() )
{
String line = inFile.next() ;
line = line.trim().replaceAll("\n", "");
line = line.trim().replaceAll("\t", "");
line = line.trim().replaceAll(" ", "");
if ( line.length() > 0 ) {
String delims = "[,]+";
String[] tokens = line.split(delims);
EmployeeParse emp = new EmployeeParse() ;
emp.setEmpID(Integer.parseInt(tokens[0]));
emp.setEmpName(tokens[1]);
emp.setEmpCity(tokens[2]);
empList.add(emp) ;
}
}
inFile.close();
}
else {
System.out.println( "File Not Found");
}
Integer rec = 0 ;
for (EmployeeParse employee : empList) {
System.out.println( "Employee-"+ ++rec +":");
System.out.println( "ID = " + employee.getEmpID());
System.out.println( "Name = " + employee.getEmpName());
System.out.println( "City = " + employee.getEmpCity());
}
}
catch ( FileNotFoundException e) {
System.out.println( "File Not Found Exception");
}
}
}
Output:
Employee-1:
ID = 101
Name = emp1
City = city1
Employee-2:
ID = 2
Name = emp2
City = city2
Employee-3:
ID = 3
Name = emp3
City = city3
Employee-4:
ID = 4
Name = emp4
City = city4
Employee-5:
ID = 5
Name = emp5
City = city5
Employee-6:
ID = 6
Name = emp6
City = city6
Python.
class Employee:
def __init__(self, id, name, city):
self.id = id
self.name = name
self.city = city
def __str__(self):
return "Name: " + str(self.name) + ". ID: " + str(self.id) + ". City: " + str(self.city)
def create_list_of_employees(file_contents):
string = _clean_line(file_contents)
if string is None:
return None
employees = []
while ";" in string:
employee_line = _read_employee(string)
if employee_line is None:
print "employee line is null, unexpected sequence."
continue
employee = _create_employee(employee_line)
if employee is None:
print "employee is null for sequence: " + employee_line
else:
employees.append(employee)
string = string.replace(employee_line + ";", "")
return employees
def _create_employee(line):
if validate_employee_string(line):
args = line.split(",")
id = args[0]
name = args[1]
city = args[2]
if validate_id(id):
return Employee(int(id), name, city)
else:
print "id is not digit"
print "invalid employee line: " + line
return None
def validate_employee_string(string):
return string is not None and string.count(",") == 2
def validate_id(id):
return id.isdigit()
def _read_employee(line):
if ";" in line:
return line[:line.find(";")]
return None
def _clean_line(line):
return "".join(line.splitlines()).replace(" ","")
contents = None
try:
with open("Employee.txt", "r") as f:
contents = f.read()
except IOError:
print "an error occurred when attempting to read the employee file."
exit()
for employee in create_list_of_employees(contents):
print employee
Output:
Name: emp1. ID: 101. City: city1
Name: emp2. ID: 2. City: city2
Name: emp3. ID: 3. City: city3
Name: emp4. ID: 4. City: city4
Name: emp5. ID: 5. City: city5
Name: emp6. ID: 6. City: city6
#include<iostream>
#include<fstream>
using namespace std;
class Employer {
public:
int empID;
string name, city;
};
int get_size();
int main () {
Employer empl[get_size()];
char c;
int Size = 0;
string str = "";
fstream f("Employee.txt", ios::in);
while (f >> c) {
if (c != ';') str += c;
else {
char *ptr = new char[str.length() + 1], *p;
strcpy(ptr, str.c_str());
p = strtok(ptr, ",");
int n = 0;
while (p) {
if (!n) {empl[Size].empID = atoi(p);}
if (n == 1) {empl[Size].name = p;}
if (n == 2) {empl[Size].city = p;}
n++;
p = strtok(0, ",");
}
delete [] ptr;
str = "";
Size++;
}
}
for (int i = 0; i < get_size(); i++)
cout << empl[i].empID << " " << empl[i].name << " " << empl[i].city << endl;
return 0;
}
int get_size() {
char c;
int size = 0;
fstream f("Employee.txt", ios::in);
while (f >> c)
if (c == ';') size++;
return size;
}
#include<iostream>
#include<fstream>
using namespace std;
class Employer {
public:
int empID;
string name, city;
};
int get_size();
int main () {
Employer empl[get_size()];
char c;
int Size = 0;
string str = "";
fstream f("Employee.txt", ios::in);
while (f >> c) {
if (c != ';') str += c;
else {
char *ptr = new char[str.length() + 1], *p;
strcpy(ptr, str.c_str());
p = strtok(ptr, ",");
int n = 0;
while (p) {
if (!n) {empl[Size].empID = atoi(p);}
if (n == 1) {empl[Size].name = p;}
if (n == 2) {empl[Size].city = p;}
n++;
p = strtok(0, ",");
}
delete [] ptr;
str = "";
Size++;
}
}
for (int i = 0; i < get_size(); i++)
cout << empl[i].empID << " " << empl[i].name << " " << empl[i].city << endl;
return 0;
}
int get_size() {
char c;
int size = 0;
fstream f("Employee.txt", ios::in);
while (f >> c)
if (c == ';') size++;
return size;
}
This is written in Swift
class Employee {
var empId : String?
var empName : String?
var empCity : String?
}
let documentDirectoryUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
let fileNameUrl = documentDirectoryUrl.URLByAppendingPathComponent("emp.txt")
var fileOpenError:NSError?
var str : NSString?
if NSFileManager.defaultManager().fileExistsAtPath(fileNameUrl.path!) {
if let fileContent = String(contentsOfURL: fileNameUrl, encoding: NSUTF8StringEncoding, error: &fileOpenError) {
str = fileContent
} else {
if let fileOpenError = fileOpenError {
println(fileOpenError)
}
}
} else {
println("file not found")
}
var empDetails : Employee?
var empList : NSMutableArray = NSMutableArray()
let arr : NSArray = str!.componentsSeparatedByString(";")
var arr2 : NSArray = NSArray()
for (index,val) in enumerate(arr) {
arr2 = val.componentsSeparatedByString(",")
empDetails = Employee()
if index != arr.count - 1 {
empDetails?.empId = arr2.objectAtIndex(0) as? String
empDetails?.empName = arr2.objectAtIndex(1) as? String
empDetails?.empCity = arr2.objectAtIndex(2) as? String
empList.addObject(empDetails!)
}
}
let emp1 = empList.objectAtIndex(0) as Employee
println("Emp ID \(emp1.empId!) Emp Name \(emp1.empName!) Emp City \(emp1.empCity!)")
Wrap all the text in single line. Split first by ;. Foreach collection item, split by , and fill the values.
- Anuj February 05, 2015