tags:

views:

123

answers:

3

i have string of 9 letters.

string myString = "123987898";

I want to retrieve frist 3 letter "123" then 2 more leters "98" and then 4 more letters "7898".

Which c# string function support this functionality.

+17  A: 

You can use Substring:

myString.Substring(0,3)
myString.Substring(3,2)
myString.Substring(5,4)

It's also possible to make it more complicated than necessary by using a combination of regular expressions and LINQ:

string myString = "123987898";
Regex regex = new Regex("(.{3})(.{2})(.{4})");
string[] bits = regex
    .Match(myString)
    .Groups
    .Cast<Group>()
    .Skip(1)
    .Select(match => match.Value)
    .ToArray();
Mark Byers
+1 for the first part. I like to Keep it simple. The second part is neat proof of concept but I would refactor it if I saw it in production code.
J.Hendrix
A: 

The best and robust way of dealing with this is to use a regex

public Regex MyRegex = new Regex(
      "(?\\d{3})(?\\d{2})(?\\d{4})",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );

Then you can access them through the Groups property of the Match instance

Match m = MyRegex.Match("123987898");
if (m.Success){
     int first3 = int.Parse(m.Groups["first3"].Value;
     int next2 = int.Parse(m.Groups["next2"].Value;
     int last4 = int.Parse(m.Groups["last4"].Value;

     /* Do whatever you have to do with first3, next2 and last 4! */
}
tommieb75
+1  A: 

There is nothing built in but it is easy enough to make yourself.

public static IEnumerable<string> SplitBySize(string value, IEnumerable<int> sizes)
{
    if (value == null) throw new ArgumentNullException("value");
    if (sizes == null) throw new ArgumentNullException("sizes");

    var length = value.Length;
    var currentIndex = 0;
    foreach (var size in sizes)
    {
        var nextIndex = currentIndex + size;
        if (nextIndex > length)
        {
            throw new ArgumentException("The sum of the sizes specified is larger than the length of the value specified.", "sizes");
        }
        yield return value.Substring(currentIndex, size);
        currentIndex = nextIndex;
    }
}

Example Usage

foreach (var item in SplitBySize("1234567890", new[] { 2, 3, 5 }))
{
    Console.WriteLine(item);
}
Console.ReadKey();
ChaosPandion