0

文字列を取得し、文字列のタイプと一致しない文字列に基づいて配列に分割する必要があります。

したがって、「asd fds 1.4#3」を使用している場合、これは次のように配列に分割されます。

stringArray[0] = "asd";
stringArray[1] = " ";
stringArray[2] = "fds";
stringArray[3] = " ";
stringArray[4] = "1";
stringArray[5] = ".";
stringArray[6] = "4";
stringArray[7] = "#";
stringArray[8] = "3";

これを達成するための最良の方法に関する推奨事項はありますか?もちろん、.ToCharArray()に基づいてループを作成することもできますが、これを実現するためのより良い方法を探していました。

ありがとうございました

4

3 に答える 3

1

正規表現を使用する:

var mc = Regex.Matches("asd fds 1.4#3", @"([a-zA-Z]+)|.");
var res = new string[mc.Count];
for (var i = 0; i < mc.Count; i++)
{
    res[i] = mc[i].Value;
}
于 2012-07-31T15:31:35.953 に答える
1

このプログラムはあなたが望む正確な出力を生成しますが、それがあなたの目標にとって一般的なものであるかどうかはわかりません。

class Program
{
    private static void Main(string[] args)
    {
        var splited = Split("asd fds 1.4#3").ToArray();
    }

    public static IEnumerable<string> Split(string text)
    {
        StringBuilder result = new StringBuilder();
        foreach (var ch in text)
        {
            if (char.IsLetter(ch))
            {
                result.Append(ch);
            }
            else
            {
                yield return result.ToString();
                result.Clear();
                yield return ch.ToString(CultureInfo.InvariantCulture);
            }
        }
    }

}
于 2012-07-31T15:40:38.173 に答える
1

正規表現とリンクの組み合わせを使用すると、次のことができます。

using System.Text.RegularExpressions;
using System.Linq;

var str="asd fds 1.4#3";
var regex=new Regex("([A-Za-z]+)|([0-9]+)|([.#]+)|(.+?)");

var result=regex.Matches(str).OfType<Match>().Select(x=>x.Value).ToArray();

Add additional capture groups to capture other differences. The last capture (.+?) is a non greedy everything else. So every item in this capture will be considered different (including the same item twice)

Update - new revision of regex

var regex=new Regex(@"(?:[A-Za-z]+)|(?:[0-9]+)|(?:[#.]+)|(?:(?:(.)\1*)+?)");

This now uses non capturing groups so that \1 can be used in the final capture. This means that the same character will be grouped if its in then catch all group.

e.g. before the string "asd fsd" would create 4 strings (each space would be considered different) now the result is 3 strings as 2 adjacent spaces are combined

于 2012-07-31T15:41:24.370 に答える