我如何在C#中对文本引入某些限制

时间:2015-03-11 18:10:27

标签: c# regex

我正在创建一个C#程序,它从xml文件中读取一串单词,创建一个文本页面并将其写入txt文件。但是,我试图引入一些限制,如果它违反了这三条规则中的任何一条,就会阻止一个单词放在文本页面上。

  1. 只能使用小写字母a-z
  2. 每个单词必须包含元音,5个或更多字母的单词必须包含2个
  3. 所有元音必须按字母顺序出现,例如节拍之类的词语会被拒绝,因为e来自
  4. 我明白为了做到这一点,我需要以某种方式读取每行的每个字符,但我不知道如何执行此操作或将这3个限制实现到代码中

    XML example input file
    <?xml version="1.0" encoding="utf-8"?>
    <pageinput>
    <format>Fill</format>       //determines what format I want the txt page to be
    <wrap>8</wrap>              //this limits how many letters per word
    <words>abc 8Ug antert bonnfk beat e</words>     //the words to be read
    </pageinput>
    

    txt文件中的预期输出 ABC antert ë

1 个答案:

答案 0 :(得分:0)

我不是正则表达爱好者,所以我要发布一些Linq和基本解决方案:

public static class Extensions {
    static readonly char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

    //#1
    public static bool IsLowerCase( this string word ){
        return word.All( c => c >= 'a' && c <= 'z' );
    }

    //#2
    public static bool ContainsVowels( this string word ) {
        int count = word.Count( c => vowels.Contains( c ) );

        return ( count >= 1 && word.Length < 5 ) || ( count > 1 && word.Length >= 5 );
    }

    //#3 
    public static bool AreVowelsOrdered( this string word ) {
        char? lastVowel = null;
        foreach ( char c in word ) {
            if ( vowels.Contains( c ) ) {
                if ( lastVowel == null || c > lastVowel )
                    lastVowel = c;
                else if ( c < lastVowel )
                    return false;                 
            }
        }

        return true;
    }
}

然后使用它们:

( "example" ).IsLowerCase( ); //true

通过将所有内容合并到一个独特的循环中,您可以对它们进行大量优化,这只是一个重点。