将字符串数组拆分

3
我有一个字符串数组string[] arr,其中包含像N36102W114383N36102W114382等值...
我想拆分每个字符串,使得值变成这样N36082W115080
最好的方法是什么?

2
什么语言?在我看来,你不想使用正则表达式来完成这个任务。 - Kimvais
2
类似这样的编程内容?(N\d+)(W\d+)(N[0-9]+)(W[0-9]+) - fardjad
这些字符串长度总是相同的吗? - default
6个回答

1

这应该适用于你。

Regex regexObj = new Regex(@"\w\d+"); # matches a character followed by a sequence of digits
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
    matchResults = matchResults.NextMatch(); #two mathches N36102 and W114383
}

0

如果这段代码无法编译,请原谅我,但我会手写字符串处理函数:

public static IEnumerable<string> Split(string str)
{
    char [] chars = str.ToCharArray();
    int last = 0;
    for(int i = 1; i < chars.Length; i++) {
        if(char.IsLetter(chars[i])) {
            yield return new string(chars, last, i - last);
            last = i;
        }
    }

    yield return new string(chars, last, chars.Length - last);
}

0
如果您每次都有固定的格式,您可以这样做:
string[] split_data = data_string.Insert(data_string.IndexOf("W"), ",")
    .Split(",", StringSplitOptions.None); 

在这里,您将一个可识别的分隔符插入到字符串中,然后按照该分隔符进行拆分。


0
使用C#中的'Split'和'IsLetter'字符串函数,这相对容易。
不要忘记编写单元测试-以下可能存在一些边角情况错误!
    // input has form "N36102W114383, N36102W114382"
    // output: "N36102", "W114383", "N36102", "W114382", ...
    string[] ParseSequenceString(string input)
    {
        string[] inputStrings = string.Split(',');

        List<string> outputStrings = new List<string>();

        foreach (string value in inputstrings) {
            List<string> valuesInString = ParseValuesInString(value);
            outputStrings.Add(valuesInString);
        }

        return outputStrings.ToArray();
    }

    // input has form "N36102W114383"
    // output: "N36102", "W114383"
    List<string> ParseValuesInString(string inputString)
    {
        List<string> outputValues = new List<string>(); 
        string currentValue = string.Empty;
        foreach (char c in inputString)
        {
            if (char.IsLetter(c))
            {
                if (currentValue .Length == 0)
                {
                    currentValue += c;
                } else
                {
                    outputValues.Add(currentValue);
                    currentValue = string.Empty;
                }
            }
            currentValue += c;
        }
        outputValues.Add(currentValue);
        return outputValues;
    }

0

如果你只是在寻找格式为NxxxxxWxxxxx的话,那么这个就可以:

Regex r = new Regex(@"(N[0-9]+)(W[0-9]+)");

Match mc = r.Match(arr[i]);
string N = mc.Groups[1];
string W = mc.Groups[2];

0
如果您使用C#,请尝试:
String[] code = new Regex("(?:([A-Z][0-9]+))").Split(text).Where(e => e.Length > 0 && e != ",").ToArray();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接