Tuesday, August 16, 2011

.NET interview questions: - How to parse the values from a string which has the format "Shiv, India, 992983"?

This is one of the most interesting topics asked by the interviewers to check how you can handle/solve this complicated situation in much easier ways. Most of the junior developers answer this question like they will run “For loop” and will check for “, (comma)” and later pass the value to the variables, this answer is also right but the interviewers will not be fully satisfied with this answer.
So the answer for the question should be by using “Split” function.

Split: - The split function of a string class allows you to extract individual values separated by specific character.

Now, let’s do a small practical demonstration to see how exactly “Split” function help to parse the value from a string in much easier way.

Let’s create a new project on console application for that Go to > New> File>Project>Windows> Select ConsoleApplication.








Now, just add the below code snippet in the main class.

staticvoid Main(string[] args)

{

string str = "Shiv,India,966457";// created a string variable and assigned values.

string[] values = newstring[2];// created array.

values = str.Split(',');// Used split function.

}

Note that, as soon as you use“Split” function in your code the VS business Intellisence will display something like below diagram.




Now, just put small debug pointer on the below line.





Later, just run your application the debug pointer will stop at the line just press F10 once and the move

mouse pointer on the values you will find result like below diagram.





In above diagram you can clearly see that now the string values are easily parsed to the array variables by using “Split” function.

View more video on different types of collections in .NET as follows: -




Get our tutorials on important .NET interview questions

Regards,

Visit for author’s more blog on Most asked .NET interview questions

No comments: