【问题标题】:Applying grammar to strings将语法应用于字符串
【发布时间】:2021-11-20 11:17:07
【问题描述】:

我正在尝试自动确定插入名称的基因,这样我就不必为每个字符串手动插入正确的基因(在本例中为名称)

例如,James 的基因是 ',而 Kennedy 的基因是 's。

我想我想说的是我想要一个更简洁的实现,让我不必为每个名字编写字符串 Genetive:friend1(2..n)

using System;

namespace Prac
{
    class Program
    {
        static void Main(string[] args)
        {
            string Friend =  "";                string last_char_Friend = "";               string Genetive_Friend = "";
            string Friend1 = "Kennedy";         string last_char_Friend1 = Friend1[^1..];   string Genetive_Friend1 = "\'s";    
            string Friend2 = "James";           string last_char_Friend2 = Friend2[^1..];   string Genetive_Friend2 = "\'";
            string Friend3 = "Ngolo Kante";     string last_char_Friend3 = Friend3[^1..];   string Genetive_Friend3 = "\'s";

        Console.WriteLine($"My friends are named {Friend1}, {Friend2} and {Friend3}");

        Console.WriteLine($"{Friend1}{Genetive_Friend1} name has {Friend1.Length} letters");
        Console.WriteLine($"{Friend2}{Genetive_Friend2} name has {Friend2.Length} letters");
        Console.WriteLine($"{Friend3}{Genetive_Friend3} name has {Friend3.Length} letters");

        for (int i = 1; i < 4; i++)
        {
            Console.WriteLine($"{Friend + i}{Genetive_Friend + i} name has {(Friend + i).Length} letters");
        }
        Console.ReadLine();
    }
}

}

我必须有一种更聪明的方法来确保将正确的语法应用于每个名称,我有一种感觉,我可以利用读取 Friend 字符串的最后一个字符,但是我如何在 Console.WriteLine 中在 ' 和 ' 之间选择?

我希望 for 循环打印与三个单独的 Console.WriteLine 行相同的内容。

这也是我第一次在 Stackoverflow 上提问,请告诉我是否违反了一些关于如何格式化 questiosn 的不成文规则。

【问题讨论】:

  • 你可以写一个函数。

标签: c# string grammar console.writeline


【解决方案1】:

这里有几个问题,首先要遍历所有参数,您应该创建一个数组(或列表或任何扩展 IEnumerable 的东西) 然后你可以迭代它。

现在按照您的示例并且不是特别精通语法,您还可以编写一个方法来检查输入字符串的最后一个字符是什么并将其转换为属格

static void Main( string[] args )
{

    string[] friends = new string[] { "Kennedy", "James", "Ngolo Kante" };
    Console.WriteLine($"My friends are named {JoinEndingWithAnd(friends)}");
    for ( int i = 1; i < friends.Length; i++ )
    {
        Console.WriteLine( $"{MakeGenitive(friends[i])} name has {friends[i].Length} letters" );
    }
    Console.ReadLine();
}

static string JoinEndingWithAnd(string[] friends)
{
    string result = friends[0];

    for ( int i = 1; i < friends.Length; i++ )
    {
        if ( i != friends.Length  - 1)
        {
            result += $" , {friends[i]}";
        }
        else
        {
            result += $" and {friends[i]}";
        }
    }

    return result;
}

static string MakeGenitive(string friend)
{
    char lastLetter = friend[^1];
    
    if( lastLetter == 's' )
    {
        return friend + "'";
    }
    return friend + "'s";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多