如何用vb.net字符串中的值替换字典项名称? [英] How can I replace a dictionary item name with its value in vb.net string?

查看:182
本文介绍了如何用vb.net字符串中的值替换字典项名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个字符串和一本字典。基本上我想遍历字典中的所有项目,如果它在字符串中找到匹配项,它会将该匹配项与字典项目的名称替换为字符串中的值。我有这段代码:

Hi guys,
I have a string and a dictionary. Basically I want to iterate through all the items in the dictionary, if it finds a match in the string, it replaces that match with the dictionaryitem's name with its value in the string. I have this code:

Dim writArg As String = Arguments(0)
                For Each DictItem In DeclaredVariables
                    MsgBox(DictItem.Key)
                    writArg = writArg.Replace(DictItem.Key, DictItem.Value)
                Next
                Return writArg



其中,declaredvariables托管变量名称和值。但它不会起作用。它不会取代它。有人可以帮忙吗?

谢谢,

-iProgramIt



编辑:

这是代码用于添加字典键。它似乎没有保存。


Where, declaredvariables hosts the variable names and values. But it won't work. It will not replace it. Can someone help?
Thanks,
-iProgramIt


This is the code for adding in the dictionary key. It doesn't seem to save.

DeclaredVariables.Add(Arguments(0), Arguments(1))

推荐答案

替换区分大小写 - 请检查您的参数string包含与您比较Hello World!的字符串完全相同的文本。不会匹配世界或世界。



我从调试器开始,看看你每次都想要替换的确切内容您要替换它的内容。



可能值得为writArg.Contains(DictItem.Key)添加一个检查,如果找到匹配则会中断。如果它没有破坏...它不匹配!
Replace is case sensitive - so check that your argument string contains exactly the same text as the string you are comparing "Hello World!" will not match "world", or "World ".

I'd start with the debugger and look at exactly what you are trying to replace each time, and exactly what you are trying to replace it in.

It might be worth adding a check for writArg.Contains(DictItem.Key) and breaking if it finds a match. If it doesn't break...it doesn't match!


最简单的方法是:

The simplest way is:
Dim DeclaredVariables As Dictionary(Of String, String) = New Dictionary(Of String, String)

DeclaredVariables.Add("wah","123")
DeclaredVariables.Add("wha","132")
DeclaredVariables.Add("awh","213")
DeclaredVariables.Add("ahw","231")
DeclaredVariables.Add("haw","321")
DeclaredVariables.Add("hwa","312")

Dim writArg As String = "wha"
writArg = DeclaredVariables(writArg)





但是我需要警告你: 这可能会导致 KeyNotFoundException [ ^ ],所以你应该通过使用尝试...捕获...结束尝试语句 [ ^ ]:



But i need to warn you: this may cause KeyNotFoundException[^], so you should avoid this by using Try... Catch... End Try statement[^]:

Try
    writArg = DeclaredVariables(writArg)
Catch ex As KeyNotFoundException
    Console.WriteLine("{0}", ex.Message)
End Try


这篇关于如何用vb.net字符串中的值替换字典项名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆