2011-11-08 169 views
3

我有一个字符串数组string[] arr,包含了像N36102W114383N36102W114382等值...
我想将每一个字符串分割使得该值就这样产生了N36082W115080分割字符串数组

这样做的最好方法是什么?

+2

什么语言?海事组织你不__want__使用正则表达式。 – Kimvais

+2

这样的事情? (N \ d +)(W \ d +)'或'(N [0-9] +)(W [0-9] +)' – fardjad

+0

你用什么语言? –

回答

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

如果你每次有固定的格式,你可以只是这样做:

string[] split_data = data_string.Insert(data_string.IndexOf("W"), ",") 
    .Split(",", StringSplitOptions.None); 

在这里,您插入分隔符识别到你的字符串,然后由这个分裂的分隔符它。

0

使用'Split'和'IsLetter'字符串函数,这在c#中相对简单。

不要忘了编写单元测试 - 以下可能有一些角落案例错误!

// 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

如果使用C#,请尝试:

String[] code = new Regex("(?:([A-Z][0-9]+))").Split(text).Where(e => e.Length > 0 && e != ",").ToArray(); 
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];