我有一个单词列表及其替换单词,例如:
服务 - >表 等
所以,如果用户写桌面,它会给结果表但是如果用户写桌面,资本 D 它不会做任何改变。我知道如何忽略大写但是世界将被替换为表,其中 t 是小写的...我希望 t 为大写。所以,如果桌面 - >表格和桌面 - >表格......我怎么能这样做?
答案 0 :(得分:1)
你可以第二次调用替换函数,第二次使用大写字母。
例如:
string result = input.Replace ("desk", "table");
result = result.Replace ("Desk", "Table");
要将字符串的第一个字符设置为大写并不是很困难。您可以使用此方法:
string lower = "desk";
string upper = char.ToUpper(lower[0]) + lower.Substring(1);
答案 1 :(得分:1)
你说你有一个单词列表及其替换单词。所以数据结构将是
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("desk","table");
dict.Add("Desk","Table");
如果这是正确的,那么以下内容将起作用
var result = dict["Desk"];
但如果你以下面的方式维持价值,
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("desk","table");
那么解决方案可能是
private void button1_Click(object sender, EventArgs e)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("desk","table");
string input = "Desk";
var dictValue = dict[input.ToLower()];
var result = IsInitCap(input.Substring(0, 1))
? System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dictValue)
: dictValue;
}
private bool IsInitCap(string str)
{
Match match = Regex.Match(str, @"^[A-Z]");
return match.Success ? true : false;
}
希望这有帮助
答案 2 :(得分:0)
您可以使用以下代码将输入字符串的第一个字母设为UpperCase,
str = str.First().ToString().ToUpper() + String.Join("", str.Skip(1));
现在,在您的情况下,使用字典数据结构来存储数据。
将输入值存储为(key)desk-&gt; table(value)
现在使用上面的代码并将第一个字母大写并存储(Desk-&gt; Table)
因此,您现在可以获得值,如桌面 - &gt;表格以及桌面 - &gt;表格。
这总是通过破坏空间复杂度来获取时间复杂度O(1)中的值。