該代碼現在運行良好。如果您需要,請隨意使用它。
問題:
撰寫一個控制臺應用程式,將文本從胡言亂語翻譯成羅馬尼亞語。胡言亂語類似于羅馬尼亞語。羅馬尼亞語文本是用胡言亂語寫成的,取原始文本并在每個元音后插入字母 p 和相應的元音。
例子:
對于輸入資料:
Apanapa aparepe meperepe.
在控制臺它會顯示:
Ana are mere
這是我的代碼:
using System;
using System.Text;
namespace FromGibberishUgly
{
class Program
{
private static string GibberishToRomanian(string text)
{
if (null == text)
return "";
const string vowels = "aeiouAEIOU";
StringBuilder sb = new StringBuilder(text.Length);
for (int i = 0; i < text.Length; i)
{
sb.Append(text[i]);
if (i < text.Length - 2 &&
vowels.Contains(text[i]) &&
text[i 1] == 'p' &&
char.ToLower(text[i 2]) == char.ToLower(text[i]))
i = 2;
}
return sb.ToString();
}
static void Main(string[] args)
{
Console.WriteLine(GibberishToRomanian(Console.ReadLine()));
}
}
}
uj5u.com熱心網友回復:
當有一個簡單的模式(vowel p vowel在你的情況下)你可以嘗試使用正則運算式:
using System.Text.RegularExpressions;
...
private static string GibberishToRomanian(string text) =>
Regex.Replace(text ?? "", @"([aeiou])p\1", "$1", RegexOptions.IgnoreCase);
演示:
Console.Write(GibberishToRomanian("Apanapa aparepe meperepe"));
結果:
Ana are mere
模式解釋:
([aeiou]) - capturing group #1 for any vowel
p - letter 'p'
\1 - value captured by group #1
編輯:如果你想堅持回圈,你可以嘗試這樣寫:
private static string GibberishToRomanian(string text) {
if (null == text)
return "";
const string vowels = "aeiouAEIOU";
StringBuilder sb = new StringBuilder(text.Length);
for (int i = 0; i < text.Length; i) {
sb.Append(text[i]);
// when facing vowel p vowel we jump over p vowel
if (i < text.Length - 2 &&
vowels.Contains(text[i]) &&
text[i 1] == 'p' &&
char.ToLower(text[i 2]) == char.ToLower(text[i]))
i = 2;
}
return sb.ToString();
}
該程式將是(小提琴)
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace FromGibberishUgly {
class Program {
//TODO: or replace it with loop solution
private static string GibberishToRomanian(string text) =>
Regex.Replace(text ?? "", @"([aeiou])p\1", "$1", RegexOptions.IgnoreCase);
static void Main(string[] args) {
Console.WriteLine(GibberishToRomanian(Console.ReadLine()));
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392463.html
上一篇:使用navArgs將Fragment轉換為DialogFragment,如何從Fragment類外部導航到DialogFragment
