我需要通過名稱「SelectOnlyVowels」創建一個方法,並在不改變下面的代碼的情況下從字符串「abc」中獲取元音。從字符串中檢索元音的方法
const string abc = "asduqwezxc"; //this is the string
foreach (var vowel in abc.SelectOnlyVowels())
{
Console.WriteLine("{0}", vowel);
}
我需要通過名稱「SelectOnlyVowels」創建一個方法,並在不改變下面的代碼的情況下從字符串「abc」中獲取元音。從字符串中檢索元音的方法
const string abc = "asduqwezxc"; //this is the string
foreach (var vowel in abc.SelectOnlyVowels())
{
Console.WriteLine("{0}", vowel);
}
看起來你正在尋找的是一個字符串的擴展方法
https://msdn.microsoft.com/en-us//library/bb383977.aspx
這裏的工作的例子。
class Program
{
static void Main(string[] args)
{
const string abc = "asduqwezxc";
foreach (var vowel in abc.SelectOnlyVowels())
{
Console.WriteLine("{0}", vowel);
}
Console.ReadLine();
}
}
public static class StringManipulation
{
public static string SelectOnlyVowels(this string text)
{
var vowels = "aeiou";
var result = "";
foreach (char c in text)
{
if (vowels.Contains(c))
{
result += c;
}
}
return result;
}
}
你只需要創建擴展方法是這樣的:
public static class StringExtensions
{
public static string SelectOnlyVowels(this string text)
{
var vowels = "aeiou";
return new String(text.Where(p => vowels.IndexOf(p.ToString(), StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray());
}
}
那麼你嘗試過什麼? – Ben
我認爲你的意思是你的老師希望你創建這個 – Jonesopolis
不幸的是,堆棧溢出不是在這裏爲你寫代碼。如果您可以舉一些您已經嘗試過的例子,我們可以告訴您您可能出錯的地方以及如何解決問題。 –