0

我正在尝试像这样在 C# 中拆分字符串

COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C

应该

word1     word2       word3      word4     word5   word5
COMMSTR1 NAC-NAM-P-C FCPANAM1 NAC-NAM-P-C  CHAZEL1 NAT-CBM-P-C

在上面它包含三个单词,有时它可能包含两个单词或一个单词。我怎样才能得到高于输出。我在下面尝试但卡住了。

class Program
        {
            static void Main(string[] args)
            {
                string str = "COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C";

                string[] words = str.Split(' ');

                 foreach(string word in words)
                    {
                        Console.WriteLine("{0}",word);
                    }

                    Console.ReadLine();

            }
4

4 回答 4

6

您可以尝试以下方法,首先将其拆分在空间上,然后用于IndexOf从单词中获取休息。:

 string str = "COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C";
 string[] words = str.Split(' ');
 List<string> list = new List<string>();
 foreach (string word in words)
   {
            int index = word.IndexOf('-'); // as per Daniel's suggestion
            list.Add(word.Substring(0,index));
            list.Add(word.Substring(index+1));
    }

//用于打印

    foreach (string tempStr in list)
    {
        Console.WriteLine(tempStr);
    }
于 2012-06-22T10:22:17.433 回答
2
    static void Main(string[] args)
    {
        string str = "COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C";

        string[] flag = str.Split(' ');
        List<string> words = new List<string>();
        foreach (string f in flag)
        {
            words.Add(f.Split('-')[0]);
            words.Add(f.Remove(0, f.IndexOf('-') + 1));
        }

        foreach (string word in words)
        {
            Console.WriteLine("{0}", word);
        }

        Console.ReadLine(); 
    }
于 2012-06-22T10:27:57.737 回答
1

带有命名组的正则表达式在这里似乎很合适:

var pattern=
    @"^(?<word1>[^-]*)-(?<word2>[^ ]*) "
    +@"(?<word3>[^-]*)-(?<word4>[^ ]*) "
    +@"(?<word5>[^-]*)-(?<word6>.*)$";
var input="COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C";
var m=Regex.Match(input,pattern);
if(m.Success)
{
    var word1=m.Groups["word1"].Value;
    var word2=m.Groups["word2"].Value;
    //etc...
}
于 2012-06-22T10:31:18.220 回答
0

你也可以使用

Split(new char[] { '-' }, 2);

仅在第一次出现 - 时拆分。所以首先是你Split(' '),然后是Split(new char[] { '-' }, 2);

@Habib.OSU 答案的修改版本将如下所示:

string str = "COMMSTR1-NAC-NAM-P-C FCPANAM1-NAC-NAM-P-C CHAZEL1-NAT-CBM-P-C";
string[] words = str.Split(' ');
List<string> list = new List<string>();
foreach (string word in words)
{
        list.AddRange(word.Split(new char[] { '-' }, 2));
}
foreach(var s in list) Console.WriteLine(s);
于 2012-06-22T10:32:03.433 回答