本文介绍了劈开两个标准的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所列的字符串。



I need to create a list of WORDS from this sample string.

A WORD is a string that starts with a period and ends with:

  1. a space or
  2. another period or
  3. end of string

Note: The key point here is - the splitting is based on two criteria - a period and a blank space

I have following program. It works fine. However, is there a simpler/more efficient/concise approach using LINQ or Regular Expressions?

CODE

        List<string> wordsCollection = new List<string>();
        string sample = " class0 .calss1 .class2 .class3.class4  .class5 class6 .class7";

        string word = null;

        int stringLength = sample.Length;
        int currentCount = 0;

        if (stringLength > 0)
        {
            foreach (Char c in sample)
            {

                currentCount++;
                if (String.IsNullOrEmpty(word))
                {
                    if (c == '.')
                    {
                        word = Convert.ToString(c);
                    }
                }
                else
                {

                    if (c == ' ')
                    {
                        //End Criteria Reached
                        word = word + Convert.ToString(c);
                        wordsCollection.Add(word);
                        word = String.Empty;
                    }
                    else if (c == '.')
                    {
                        //End Criteria Reached
                        wordsCollection.Add(word);
                        word = Convert.ToString(c);
                    }
                    else
                    {
                        word = word + Convert.ToString(c);
                        if (stringLength == currentCount)
                        {
                            wordsCollection.Add(word);
                        }
                    }
                }

            }
        }

RESULT

        foreach (string wordItem in wordsCollection)
        {
            Console.WriteLine(wordItem);

        }

Reference:

  1. Splitting up a string, based on predicate
  2. Is there a better way to get sub-sequences where each item matches a predicate?
  3. Linq based generic alternate to Predicate<T>?
解决方案

You can do this with a regular expression.

Code

Regex regex = new Regex(@"\.[^ .]+");
var matches = regex.Matches(sample);
string[] result = matches.Cast<Match>().Select(x => x.Value).ToArray();

See it working online: ideone

Result

.calss1
.class2
.class3
.class4
.class5
.class7

Explanation of Regular Expression

\.      Match a dot
[^. ]+  Negative character class - anything apart from space or dot (at least one)

Related

这篇关于劈开两个标准的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 06:58
查看更多