Is there a way to parse strings better?

Since a format is known, and shouldn’t change Substring should work for you

string data = "bsarbirthd0692";
string name, desc, date;
name = data.Substring(0, 4);
desc = data.Substring(4, 6);
date = data.SubString(10);

EDIT

There’s also extension methods you can create to do what ever you want. This is obviously more complex than previous suggestion

public static class StringExtension
{
    /// <summary>
    /// Returns a string array of the original string broken apart by the parameters
    /// </summary>
    /// <param name="str">The original string</param>
    /// <param name="obj">Integer array of how long each broken piece will be</param>
    /// <returns>A string array of the original string broken apart</returns>
    public static string[] ParseFormat(this string str, params int[] obj)
    {
        int startIndex = 0;
        string[] pieces = new string[obj.Length];
        for (int i = 0; i < obj.Length; i++)
        {
            if (startIndex + obj[i] < str.Length)
            {
                pieces[i] = str.Substring(startIndex, obj[i]);
                startIndex += obj[i];
            }
            else if (startIndex + obj[i] >= str.Length && startIndex < str.Length)
            {
                // Parse the remaining characters of the string
                pieces[i] = str.Substring(startIndex);
                startIndex += str.Length + startIndex;
            }

            // Remaining indexes, in pieces if they're are any, will be null
        }

        return pieces;
    }
}

Usage 1:

string d = "bsarbirthd0692";
string[] pieces = d.ParseFormat(4,6,4);

Result:

enter image description here

Usage 2:

string d = "bsarbirthd0692";
string[] pieces = d.ParseFormat(4,6,4,1,2,3);

Results:

enter image description here

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)