[英]Replace 0 - 10 numbers in string with words in C#
我面臨的問題是我必須將輸入中的 0 - 10 替換為它們各自的單詞,如“2” - 兩個,這將是一個字符串。 示例:當輸入顯示“11 個蘋果和 2 個芒果”時,我得到的 output 是“一個蘋果和兩個芒果”。 預期 Output:“11 個蘋果和兩個芒果”。 這是我的一次嘗試,但失敗了。
string str = Console.ReadLine();
string[] strArr = str.split(" ");
Regex rgx = new Regex("^[0-9]{2}");
var val = rgx.isMatch(strAtr[i]);
if(!val){
StringBuilder sb = new StringBuilder(str);
sb.Replace("0", "zero");
sb.Replace("1", "one");
sb.Replace("2", "two");
sb.Replace("3", "three");
sb.Replace("4", "four");
sb.Replace("5", "five");
sb.Replace("6", "six");
sb.Replace("7", "seven");
sb.Replace("8", "eight");
sb.Replace("9", "nine");
sb.Replace("10", "ten");
}
Console.WriteLine(sb.ToString());
我將在下面留下我的原始答案,這是一個很好的答案,看起來你在問這個問題,直到你在評論中澄清了一些事情。
我相信這回答了你的問題:
const string mangoesPattern = @"\d+";
var mangoesRegex = new Regex(mangoesPattern);
const string mangoesSource = "I have 5 apples, 11 mangoes, 675 oranges, 3 grapes and 27 coconuts";
var mangoesDictionary = new Dictionary<int, string>
{
{0, "zero"},
{1, "one"},
{2, "two"},
{3, "three"},
{4, "four"},
{5, "five"},
{6, "six"},
{7, "seven"},
{8, "eight"},
{9, "nine"},
{10, "ten"},
};
var mangoesMatches = mangoesRegex.Matches(mangoesSource);
var buffer = new StringBuilder();
var lastProcessedIndex = 0;
var originalStringLength = mangoesSource.Length;
foreach (var match in mangoesMatches.Cast<Match>())
{
var numGroup = match.Groups[0];
var num = int.Parse(numGroup.ToString()); //it's necessarily a number, so it should work
if (mangoesDictionary.ContainsKey(num))
{
buffer.Append(mangoesSource.Substring(lastProcessedIndex, numGroup.Index - lastProcessedIndex));
buffer.Append(mangoesDictionary[num]);
lastProcessedIndex = numGroup.Index + numGroup.Length;
}
}
//pick up the rest of the string
buffer.Append(mangoesSource.Substring(lastProcessedIndex, originalStringLength - lastProcessedIndex));
它在您的源字符串中查找任何 integer 子字符串,然后遍歷匹配項和組,檢查 integer 的值和您要翻譯的數字之間是否存在翻譯。 如果有,它會進行替換。
翻譯后,原文出處:
I have 5 apples, 11 mangoes, 675 oranges, 3 grapes and 27 coconuts
結束為:
I have five apples, 11 mangoes, 675 oranges, three grapes and 27 coconuts
這是我的原始答案,當我認為您的問題是關於“如何將數字轉換為文本”時。
順便說一句,你真的需要充實你的問題。 閱讀所有評論並解決您的問題。 使用我的蘋果和芒果串作為你想要的行為的例子
這看起來像是一項家庭作業。 我不做其他人的功課,但我會給出一大堆提示作為答案。
首先考慮問題空間:
這應該足以讓您編寫一些代碼。
如果您考慮一下,則不需要那么多字符串。 20 個 0-19,然后 8 個 20-90。 然后是“百”、“千”、“百萬”等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.