【发布时间】:2014-04-04 04:54:47
【问题描述】:
首先 - 这是一个家庭作业问题。只是把它拿出来。尝试在 C# 中构建 Pig Latin Translator,我们必须使用正则表达式替换,但我遇到了一些问题。不允许使用 Split 方法获取单词数组。我们必须使用 Regex 类型的静态方法 Replace。应保留空格、标点符号换行符等。大写的单词应该保持不变。对于那些不熟悉 Pig Latin 规则的人-
- 如果字符串以元音开头,则在字符串中添加“way”。 (元音是 a,e,i,o,u) 示例:“橙色”的 Pig-Latin 是“orangeway”,“eating”的 Pig-Latin 是“eatingway”
- 否则,找到第一个出现的元音,将元音之前的所有字符移动到单词的末尾,并添加“ay”。 (在单词“y”的中间也算元音,但不在开头) 示例:“story”的猪拉丁语是“orystay”,因为字符“st”出现在第一个元音之前; “水晶”的猪拉丁语是“ystalcray”,但“黄色”的猪拉丁语是“ellowyay”。
- 如果没有元音,请添加“ay”。示例:“mph”的 Pig-Latin 为“mphay”,RPM 的 Pig-Latin 为 RPMay
我有大量注释掉的代码,所以为了便于阅读,我将其删除。 我的测试句是“吃猴子便便。”我得到“Ewayaayt moaynkeayy poayoay。” 我知道正则表达式是“贪婪的”,但我不知道如何让它只用它找到的第一个元音就停止。也使用文本框。
namespace AssignmentPigLatin
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
OriginalTb.Text = "Eat monkey poo.";
}
private void translateButton_Click(object sender, RoutedEventArgs e)
{
string vowels = "[AEIOUaeiou]";
var regex = new Regex(vowels);
var translation = regex.Replace(OriginalTb.Text, TranslateToPigLatin);
PigLatinTb.Text = translation;
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
OriginalTb.Text = "";
PigLatinTb.Text = "";
}
static string TranslateToPigLatin(Match match)
{
string word = match.ToString();
string firstLetters = word.Substring(0, match.Length);
string restLetters = word.Substring(firstLetters.Length - 1, word.Length-1);
string newWord;
if (match.Index == 0)
{
return word + "way";
}
else
{
return restLetters + firstLetters + "ay";
}
}
}
}
【问题讨论】:
-
好一个。我做完。将发布答案