[英]C# replacing a string
我有一个单词列表及其替换单词,例如:
桌子 - >桌子等
因此,如果用户写入桌面 ,它将给出结果表,但如果用户使用大写D写桌面 ,则不会做任何更改。 我知道如何忽略大写但是世界将被替换为表格 ,其中t是小写的...我希望t是大写的。 所以如果桌子 - >桌子和桌子 - >桌子......我怎么能这样做?
您可以第二次调用替换函数,第二次使用大写字母。
例如:
string result = input.Replace ("desk", "table");
result = result.Replace ("Desk", "Table");
要将字符串的第一个字符设置为大写并不是很困难。 你可以使用这个方法:
string lower = "desk";
string upper = char.ToUpper(lower[0]) + lower.Substring(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;
}
希望这可以帮助
您可以使用以下代码将输入字符串的第一个字母设为UpperCase,
str = str.First().ToString().ToUpper() + String.Join("", str.Skip(1));
现在,在您的情况下,使用Dictionary数据结构来存储数据。
存储输入值(key)desk-> table(value)
现在使用上面的代码并使第一个字母大写并存储它(Desk-> Table)
因此,您现在可以获得值,如桌面 - >表格和桌面 - >表格。
这总是通过牺牲空间复杂度来获取时间复杂度O(1)中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.