有没有一种方法来解析字符串比较好?比较好、字符串、方法来

由网友(人潮拥挤、我该远离)分享简介:我不知道是否有一个内置的方式在.NET中解析字符串位。I'm wondering if there's a built in way in .NET to parse bits of a string.举个例子,我有以下字符串:Take for example I have the following strin...

我不知道是否有一个内置的方式在.NET中解析字符串位。

I'm wondering if there's a built in way in .NET to parse bits of a string.

举个例子,我有以下字符串:

Take for example I have the following string:

"bsarbirthd0692"

由将被交叉引用到数据以后以下部分:

made up of the following parts that will be cross referenced to data later:

Indexes   Purpose
0-3       (name)
4-9       (description)
10-13     (date mm-yy)

我希望的东西,原生这样的:

I'm hoping for something native like:

string name, desc, date;
string.ParseFormat("{0:4}{1:5}{2:4}", "bsarbirthd0692", out name, out desc, out date);

时有原生的方式来做到这一点。NET或流行的库?

Is there a native way to do this in .NET or a popular library?

推荐答案

由于格式是已知的,并且不应更改子字符串应该为你工作。

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);

修改

还有扩展方法可以创建做什么都想要。这显然​​比previous建议

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;
    }
}

用法1:

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

结果:

用法2:

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

结果:

阅读全文

相关推荐

最新文章