需要拆分具有特定例外的字符串

本文关键字:字符串 拆分 | 更新日期: 2023-09-27 18:33:24

帮助,我需要拆分:

AAA 'BBB C' DD EE FG HJJ

保留报价空间

我尝试使用.拆分(" ") 并以

AAA'BBB

C'DD

EE
FG
HJJ

我所期望的是

AAA'BBB
C'DD

EE
FG
HJJ

谁能帮我?

需要拆分具有特定例外的字符串

你可以用" "拆分,那么如前所述,你会得到错误的结果,所以试着在这个结果周围循环,找到所有以'字符开头的元素,然后合并在一起,直到你到达以'字符结尾的元素。不要忘记在它们之间留一个空格。

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

2)下一页 将所有这些引用的单词替换为原始文本中的任何内容。所以你只剩下单词和空格。注意 - 您替换引用的单词的点有 2 个空格(前导和尾随)。因此,使用修剪只包含 1 个空格。

3)接下来使用您在空格上的拆分来获取单个单词

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

我不知道

你是想将拆分的字符串存储在内存中,还是从另一边,你只想显示它。我制作了一个函数的代码,该函数将第一个字符串(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);
            }
        }
    }

我希望这有帮助!