How do you split a string based on a character without using string.split function ?

 Posted by Bharathi Cherukuri on 6/5/2012 | Category: ASP.NET Interview questions | Views: 1676 | Points: 40
Answer:

You can split a string based on a character by the following way:
System.Text.RegularExpressions namespace have to be imported to use Regex.Split() method.

Example:

using System;

using System.Text.RegularExpressions;

class Program
{
static void Main()
{
//
// String containing numbers.
//
string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer.";
//
// Get all digit sequence as strings.
//
string[] digits = Regex.Split(sentence, @"\D+");
//
// Now we have each number string.
//
foreach (string value in digits)
{
//
// Parse the value to get the number.
//
int number;
if (int.TryParse(value, out number))
{
Console.WriteLine(value);
}
}
}
}

Output

10
20
40
1


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response