gpt4 book ai didi

c# - 如何将字符串中单词之间的每个数字作为单独的值进行替换

转载 作者:行者123 更新时间:2023-12-03 19:34:04 24 4
gpt4 key购买 nike

首先我要说的是,我不是在问如何将整数值转换为字符串短语。

我的问题是如何获取字符串中单词之间存在的每个数字作为单独的值,以四千六百万替换 46 000 000,用七千万替换 70 000 000。为了使其更容易并且不会混淆,例如,如果字符串值已经存在:

string val1 = "replace1";
string val2 = "replace2";

并输入字符串:

  string inputStr = "distance from the Sun ranging from 46 000 000 to 70 000 000 km";

得到这个结果:

distance from the Sun ranging from replace1 to replace2 km

我不是问如何将值替换为其他值,我的问题是如何从字符串中提取现有数字作为单独的值以在之后替换它。

string foundNum1 = "46 000 000";
string foundNum2 = "70 000 000";

只有这样我才能使用替换方法:

string f1 = inputStr.Replace(foundNum1, val1);
string outStr = f1.Replace(foundNum2, val2);

最佳答案

以下是您需要转换的任何数字的完整答案:

 public static string NumberToWords(int number)
{
if (number == 0)
return "zero";

if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));

string words = "";

if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}

if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}

if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}

if (number > 0)
{
if (words != "")
words += "and ";

var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}

return words;
}


public string ConvertStringNumbersToWrittenForm(string inputStr)
{
var regex = new Regex(@"[\d][\d ]+[\d]");

var matches = regex.Matches(inputStr);
string newString = inputStr;
foreach (var match in matches)
{
string matchStr = match.ToString();
//eliminate spaces
matchStr = matchStr.Replace(" ", string.Empty);
newString = newString.Replace(match.ToString(), NumberToWords(Convert.ToInt32(matchStr)));
}

return newString;
}

要使用它,您可以调用:

string wordString = ConvertStringNumbersToWrittenForm("distance from the Sun ranging from 46 000 000 to 70 000 000 km");

wordString 将是结果字符串,其中包含数字的书面文字。

关于c# - 如何将字符串中单词之间的每个数字作为单独的值进行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com