删除并添加字符串中的字母

时间:2018-11-21 19:32:42

标签: c# string

我正在尝试解决C#中的问题。

这是任务:

  
      
  • 如果单词开始带有元音(a,e,i,o,u或A,E,I,O,U),则删除   第一个字母并将其附加到末尾,然后添加“ che” 。如果你有   “橙色”一词翻译为“ rangeoche”
  •   
  • 如果单词开始带有辅音(即不是元音),请在单词的末尾附加“ che” 。例如,单词“鸡”变成   “鸡肉”。
  •   
  • 如果单词的字母为偶数,请在其末尾附加一个“ e”
  •   
     

打印翻译后的句子。

示例:

Hello there Amy

输出:

Helloche thereche myAche

这是我到目前为止所做的:

        string Sentence = Console.ReadLine();
        string[] output = Sentence.Split(' ');
        char letter;
        string che = "che";
        StringBuilder sb = new StringBuilder(Sentence);
        foreach (string s in output)
        {
            letter = s[0];

            if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i'
            || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U')
            {
             //  Console.WriteLine("first char of the word is a vowel");
            }
            else
            {
                sb.Insert(s.Length,che);
              //  Console.WriteLine("first char of a word is a consonant");
            }

            if (s.Length % 2 == 0)
            {
              //  Console.WriteLine("the word has even numbers of letters");
            }
            //Console.WriteLine(firstchar);
            int currentWordLength = s.Length;

        }
        Console.WriteLine(sb);

问题是我不能添加"che"或删除单词的元音,因为由于这些变化,索引正在移动。我只能更改第一个单词。我的if是正确的,因为如果我取消注释Console.Writelines,它们就会扫描每个单词。 我只是在为每个单词添加/删除而苦苦挣扎。你能给我指出正确的方向吗?

7 个答案:

答案 0 :(得分:1)

首先,我建议您更改翻译代码,使其具有作用于单词而不是整个句子的功能。因此,foreach (string s in output)中的代码应移至仅作用于该字符串的另一个函数。并且不要尝试操纵传递给它的字符串,而是根据您列出的逻辑创建一个新的字符串。创建翻译后的字符串后,将其返回给调用方。然后,调用者将从返回的每个译文中重建句子。

答案 1 :(得分:1)

我建议您创建StringBuilder对象,并将适当的string附加到IF条件中。尝试以下代码:

    string Sentence = Console.ReadLine();
    string[] output = Sentence.Split(' ');
    char letter;
    string che = "che";
    StringBuilder sb = null;
    Console.WriteLine("\n");
    string strFinal = "";
    foreach (string s in output)
    {
        letter = s[0];
        sb = new StringBuilder(s);

        if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i'
        || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U')
        {
            // Console.WriteLine("first char of the word is a vowel");
            string s1 = sb.Remove(0, 1).ToString();
            sb.Insert(s1.Length, letter);
            sb.Insert(sb.Length, che);
        }
        else
        {
            // Console.WriteLine("first char of a word is a consonant");
            sb.Insert(s.Length, che);
        }

        if (s.Length % 2 == 0)
        {
            // Console.WriteLine("the word has even numbers of letters");
            // sb.Insert(s.Length, "e");
            sb.Insert(sb.Length, "e");
        }
        //Console.WriteLine(firstchar);
        int currentWordLength = s.Length;

        strFinal += sb + " ";
    }

    Console.WriteLine(strFinal);
    Console.ReadKey();

答案 2 :(得分:0)

让我们从提取方法的帮助下将初始问题分解为较小的问题:

  using using System.Text.RegularExpressions;

  ...

  private static String ConvertWord(string word) {
    //TODO: Solution here 
    return word; // <- Stub
  }

  private static String ConvertPhrase(string phrase) {
    // Regex (not Split) to preserve punctuation: 
    // we convert each word (continued sequence of letter A..Z a..z or ')
    // within the original phrase 
    return Regex.Replace(phrase, @"[A-Za-z']+", match => ConvertWord(match.Value));

    // Or if there's guarantee, that space is the only separator:
    // return string.Join(" ", phrase
    //   .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) 
    //   .Select(item => ConvertWord(item)));
  }

现在是实现ConvertWord的时候了:

  private static String ConvertWord(string word) {
    // Do not forget of special cases - e.g. empty string
    if (string.IsNullOrEmpty(word)) 
      return "chee";

    //  If the word has even number of letters append one more "e" to the end of it. 
    string suffix = word.Length % 2 == 0 ? "chee" : "che"; 

    // To cases: starting from vowel / consonant
    char letter = char.ToUpper(word[0]); 

    if (letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || letter == 'U')
      return word.Substring(1) + word.Substring(0, 1) + suffix;
    else
      return word + suffix;
  }

最后

  string Sentence = Console.ReadLine();

  Console.Write(ConvertPhrase(Sentence));

用于测试输入

"It's just a simple test (demo only): nothing more!"

会得到

t'sIchee justchee ache simplechee testchee (demochee nlyochee): nothingche morechee!

答案 3 :(得分:0)

if结束之前,您不得更改单词。您需要测试所有条件并将结果保存到另一个值中,最后对单词进行更改:

foreach (string s in output)
    {
        letter = char.ToLower(s[0]);
        bool isVowel = false;
        bool isEven = false;

        if (letter == 'a' || letter == 'e' || letter == 'i'
         || letter == 'o' || letter == 'u')
        {
           isVowel = true;
        }            

        if (s.Length % 2 == 0)
        {
            isEven = true;
        }

        //Now you can change the word
        if (isVowel)
        {
            //Do What you want
        }

        if (isEven)
        {
            //Do What you want
        }

        //Console.WriteLine(firstchar);
        int currentWordLength = s.Length;

    }

答案 4 :(得分:0)

使用明显的扩展方法:

public static class ExtensionMethods {
    // ***
    // *** int Extensions
    // ***
    public static bool IsEven(this int n) => n % 2 == 0;

    // ***
    // *** String Extensions
    // ***
    public static bool StartsWithOneOf(this string s, HashSet<char> starts) => starts.Contains(s[0]);
    public static string Join(this IEnumerable<string> strings, string sep) => String.Join(sep, strings);
}

您可以使用LINQ来处理规则:

var vowels = "aeiouAEIOU".ToHashSet();

var ans = src.Split(' ')
             .Select(w => (w.StartsWithOneOf(vowels) ? w.Substring(1)+w[0] : w)+"che"+(w.Length.IsEven() ? "e" : ""))
             .Join(" ");

答案 5 :(得分:-1)

我会说将逻辑分解为特定的单元,以便您可以编写测试,

    static void Main(string[] args)
    {
        var input = Console.ReadLine();
        var inputs = input.Split(' ');
        var sentence = string.Join(" ", inputs.Select(ConvertWord));
        Console.Write(sentence);
        Console.Read();
    }

    internal static string ConvertWord(string input)
    {
        const string che = "che";

        var vowels = new List<string>
        {
            "a","A", "e", "E", "i", "I", "o", "O", "u", "U"
        };

        var firstChar = input.First();

        var startsWithVowel = vowels.SingleOrDefault(a => a.Equals(firstChar));

        string rule2String, output;

        if (string.IsNullOrEmpty(startsWithVowel))
        {
            output = input + che;
        }

        else
        {
            output = input.Substring(1) + startsWithVowel + che;
        }

        rule2String = IsLengthEven(input)
            ? output + "e"
            : output
        ;

        return rule2String;
    }

    internal static bool IsLengthEven(string input)
    {
        return input.Length % 2 == 0;
    }

希望这会有所帮助! PS:我还没有介绍过边缘案例

答案 6 :(得分:-1)

我建议使用String.Join,并将Linq与String.Format结合使用。然后解决方案很简单:

    private String convertSentence() {
        var sentence = "Hello there Amy";
        var vowels = "aeiou";
        var che = "che";

        return String.Join(" ", (
                from s in sentence.Split(' ')
                let moveFirstToEnd = vowels.Contains(s.ToLower()[0]) && s.Length > 1 
                select String.Format("{0}{1}{2}{3}"
                    , moveFirstToEnd ? s.Substring(1) : s
                    , moveFirstToEnd ? s.Substring(0, 1) : String.Empty
                    , che
                    , s.Length % 2 == 0 ? "e" : String.Empty
                )
            )
        );
    }