代码之家  ›  专栏  ›  技术社区  ›  AAH-Shoot

C字符串拆分

  •  4
  • AAH-Shoot  · 技术社区  · 15 年前

    如果我有一根绳子: str1|str2|str3|srt4 然后用解析 | 作为分隔符。我的输出将是 str1 str2 str3 str4 .

    但如果我有一根绳子: str1||str3|str4 输出将是 str1 str3 str4 . 我希望我的输出是这样的 str1 null/blank str3 str4 .

    我希望这是有道理的。

    string createText = "srt1||str3|str4";
    string[] txt = createText.Split(new[] { '|', ',' },
                       StringSplitOptions.RemoveEmptyEntries);
    if (File.Exists(path))
    {
        //Console.WriteLine("{0} already exists.", path);
        File.Delete(path);
        // write to file.
    
        using (StreamWriter sw = new StreamWriter(path, true, Encoding.Unicode))
        {
            sw.WriteLine("str1:{0}",txt[0]);
            sw.WriteLine("str2:{0}",txt[1]);
            sw.WriteLine("str3:{0}",txt[2]);
            sw.WriteLine("str4:{0}",txt[3]);
        }
    }
    

    产量

    str1:str1
    str2:str3
    str3:str4
    str4:"blank"
    

    这不是我要找的。这是我想要的代码:

    str1:str1
    str2:"blank"
    str3:str3
    str4:str4
    
    4 回复  |  直到 15 年前
        1
  •  4
  •   Margus    15 年前

    最简单的方法是 Quantification :

    using System.Text.RegularExpressions;
    ...
    String [] parts = new Regex("[|]+").split("str1|str2|str3|srt4");
    

    “+”可以去掉它。

    Wikipedia : “+”加号表示前面有一个或多个元素。例如,ab+c匹配“abc”、“abbc”、“abbbc”等,但不匹配“ac”。

    形式 msdn: The Regex.Split 方法类似于string.split方法,但split在由正则表达式而不是一组字符确定的分隔符处拆分字符串。输入字符串被拆分尽可能多。如果在输入字符串中找不到模式,则返回值包含一个值为原始输入字符串的元素。

    其他愿望可通过以下方式实现:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1 {
        class Program{
            static void Main(string[] args){
                String[] parts = "str1||str2|str3".Replace(@"||", "|\"blank\"|").Split(@"|");
    
                foreach (string s in parts)
                    Console.WriteLine(s);
            }
        }
    }
    
        2
  •  9
  •   John Kugelman Michael Hodel    15 年前

    试试这个:

    str.Split('|')
    

    没有 StringSplitOptions.RemoveEmptyEntries 通过了,你想怎么用就怎么用。

        3
  •  8
  •   Lee    15 年前

    这应该会起作用…

    string s = "str1||str3|str4";
    string[] parts = s.Split('|');
    
        4
  •  1
  •   slugster Joey Cai    15 年前

    尝试如下操作:

    string result = "str1||str3|srt4";
    List<string> parsedResult = result.Split('|').Select(x => string.IsNullOrEmpty(x) ? "null" : x).ToList();
    

    当使用 Split() 数组中的结果字符串将为空(非空)。在这个例子中,我测试了它,并用实际的单词替换了它。 null 因此,您可以看到如何用另一个值替换。