Click here to Skip to main content
15,897,291 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to split a string into digit and char
eg: string =jan30
output should be month =jan date =30

What I have tried:

i want to split a string into digit and char
eg: string =jan30
output should be month =jan date =30
Posted
Updated 1-Dec-20 10:46am
v2
Comments
PIEBALDconsult 1-Dec-20 9:10am    
Definitely Regular Expressions.

Try a regex:
C#
using System.Text.RegularExpressions;
...
/// <summary>
///  Regular expression built for C# on: Tue, Dec 1, 2020, 10:54:16 AM
///  Using Expresso Version: 3.0.4750, http://www.ultrapico.com
///  
///  A description of the regular expression:
///  
///  [month]: A named capture group. [[a-zA-Z]+]
///      Any character in this class: [a-zA-Z], one or more repetitions
///  [day]: A named capture group. [\d+]
///      Any digit, one or more repetitions
///  
///
/// </summary>
public static Regex GetMonthAndDay = new Regex(
      "(?<month>[a-zA-Z]+)(?<day>\\d+)",
    RegexOptions.IgnoreCase
    | RegexOptions.Multiline
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );
...
            Match m = GetMonthAndDay.Match("Jan30");
            if (m.Success)
                {
                string month = m.Groups["month"].Value;
                string day = m.Groups["day"].Value;
                }


Get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 

A Regular Expression is probably the best way to go. Personally, I dislike the syntax, it looks like a cat has walked across the top rows of the keyboard. Fortunately, if your string format is constant, you can simply split the string on the first digit found and return the result as a value Tuple (string month, string date). Something like this.


C#
private static (string month, string date) SplitMonthAndDayOfMonth(string s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsDigit(s[i]))
            {
                return (s.Substring(0, i), s.Substring(i));
            }
        }
        return (string.Empty, string.Empty);
    }

    private static void Main(string[] args)
    {
        string s = "Jan30";
        var (month, day) = SplitMonthAndDayOfMonth(s);
        Console.WriteLine($"Month is {month} date is {day}");
        Console.ReadLine();
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900