[英]Applying grammar to strings
我正在嘗試自動確定插入名稱的基因,這樣我就不必為每個字符串手動插入正確的基因(在這種情況下是名稱)
例如,詹姆斯的基因是 ',肯尼迪的基因是 '。
我想我想說的是我想要一個更簡潔的實現,讓我不必為每個名字編寫字符串 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 的不成文規則。
這里有幾個問題,首先要遍歷所有 arguments 你應該創建一個數組(或列表或任何擴展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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.