需要拆分具有特定异常的字符串

时间:2016-02-06 09:06:23

标签: c# split

帮助,我需要拆分:

  

aaa'bbb c'dd ee fg hjj

在报价单上保留空格

我尝试使用.Split(“”)并最终使用

  

AAA
'BBB
C'
DD EE

FG
HJJ

我的期望

  

aaa
'bbb c'
dd
ee
fg
hjj

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

尝试这个逻辑: 1)找到第一个引用'然后是下一个引文' 你会在引文中得到这个词。 运行从第1个字符开始到上述活动的文本长度的循环,以提取引号和引号中的所有单词。存储在数组中。您随后搜索报价应从最后一个报价位置+ 1

开始

2)下一步将所有这些引用的单词替换为原始文本中的任何内容。 所以你留下的话语和仅限空间。 记住它 - 您替换引用的单词的点有2个空格(前导和尾随)。 因此,使用trim只有1个空格。

3)接下来在白色空间上使用你的分割来获得单词

4)现在结合第1点和第1点的结果。第3点获得最终结果

答案 1 :(得分:0)

你可能只是用“”拆分然后如上所述你会得到错误的结果所以尝试循环这个结果找到所有以'字符开头的元素然后合并在一起直到你到达以'字符结尾的元素。不要忘记在它们之间留一个空格。

答案 2 :(得分:0)

我不知道你是想将分裂的字符串存储在内存中,还是由其他方面存储,你只想显示它。我已经创建了一个函数代码,它将第一个字符串(aa'bbb c'dd ee fg hjj)拆分为三个字符串,并将它们存储在另一个字符串数组中。然后用空格再次分割最后一个并再次存储:

 static void exampleFunction()
    {
        const int MAXNUM = 20; //The max amount of elements in the second array strings.
        int count = 0;
        int secondCount = 0;
        string text = "aaa 'bbb c' dd ee fg hjj";
        string[] firstTextSplitted = { "" };
        string[] secondTextSplitted = new string[MAXNUM];

        firstTextSplitted = text.Split('\''); //We obtain the following strings: "aaa", "bbb c" and "dd ee fg hjj".

        for (count = 0; count < 3; count++) //We obtain separately the three strings from the first string array.
        {
            if (count == 2) //If we are in the last one, we must split it again and store each element in the followings.
            {
                secondCount = count;

                foreach (string element in firstTextSplitted[count].Split(' '))
                {
                    secondTextSplitted[secondCount] = element;
                    secondCount++;
                }
            }
            else
            {
                secondTextSplitted[count] = firstTextSplitted[count];
            }
        }

        foreach (string element in secondTextSplitted) //We print each string value from the second string array, if we dont match a null value.
        {
            if (element != null)
            {
                Console.WriteLine(element);
            }
        }
    }

我希望这有帮助!