言語処理100本ノック03(C#)

03. 円周率

"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.

C#

  • 正規表現System.Text.RegularExpressionsパッケージを使う
using System.Text;
using System.Text.RegularExpressions;

public class Hello{
    public static void Main(){
        string text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.";
        string[] words = text.Split(" ");
        var pattern = @"[^a-zA-z0-9]";
        var resultList = new List<int>();
        foreach(var word in words){
            var charList = word.Split("").AsList();
            int i=0;
            foreach(var c in charList){
                if(!Regex.IsMatch(c, pattern)){
                    charList.RemoveAt(i);
                    continue;
                }
                i++;
            }
            resultList.Add(charList.Count());
        }
        resultList.Select(item => System.Console.WriteLine(item + " "));
    }
}