Perform Trim() while using Split()

后端 未结 7 1202
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 15:53

today I was wondering if there is a better solution perform the following code sample.

string keyword = \" abc, foo  ,     bar\";
string match = \"foo\";
str         


        
相关标签:
7条回答
  • 2020-12-23 16:37

    If spaces just surrounds the words in the comma separated string this will work:

    var keyword = " abc, foo  ,     bar";
    var array = keyword.Replace(" ", "").Split(',');
    if (array.Contains("foo"))
    {
        Debug.Print("Match");
    }
    
    0 讨论(0)
  • 2020-12-23 16:39

    You're going to find a lot of different methods of doing this and the performance change and accuracy isn't going to be readily apparent. I'd recommend plugging them all into a testing suite like NUnit in order both to find which one comes out on top AND which ones are accurate.

    Use small, medium, and large amounts of text in loops to examine the various situations.

    0 讨论(0)
  • 2020-12-23 16:41

    I would suggest using regular expressions on the original string, looking for the pattern "any number of spaces followed by one of your delimiters followed by one or more spaces" and remove those spaces. Then split.

    0 讨论(0)
  • 2020-12-23 16:44

    Another possible option (that avoids LINQ, for better or worse):

    string line = " abc, foo  ,     bar";
    string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim());
    

    However, if you just need to know if it is there - perhaps short-circuit?

    bool contains = line.Split(',').Any(p => p.Trim() == match);
    
    0 讨论(0)
  • 2020-12-23 16:45

    Try this:

    string keyword = " abc, foo  ,     bar";
    string match = "foo";
    string[] split = Regex.Split(keyword.Trim(), @"\s*[,;]\s*");
    if (split.Contains(match))
    {
        // do stuff
    }
    
    0 讨论(0)
  • 2020-12-23 16:53
    var parts = line
        .Split(';')
        .Select(p => p.Trim())
        .Where(p => !string.IsNullOrWhiteSpace(p))
        .ToArray();
    
    0 讨论(0)
提交回复
热议问题