c# - 将字符串显示为下划线但保留值

标签 c# regex windows-phone-7

我正在编写一个基本的刽子手游戏。我想存储一个字符串 Word 作为用户要查找的单词。我的问题是我想将这个词显示为下划线(就像你在纸质刽子手中所做的那样)但保留它的字符串值。我的一个 friend 说这可以通过正则表达式来完成,但研究它似乎对我没有帮助。

最佳答案

按照 Farinha 的建议,但使用 HashSet

一些重要的要点:我们正在使用 HashSet因为最终字母可以有两种状态:发现(存在于 HS 中)或未发现(不存在)。我们初始化 HashSet作为参数传递 StringComparer.InvariantCultureIgnoreCase因为我们考虑 Ll是同一件事。使用 StringComparer.InvariantCultureIgnoreCase我们必须使用 HashSet<string> (string 的 HS)而不是 HashSet<char> (char 的 HS)。所以当使用 discovered.Contains()我们必须转换 c charstringToString

static string ConvertWord(string word, HashSet<string> discovered)
{
    StringBuilder sb = new StringBuilder(word.Length);

    foreach (char c in word)
    {
        if (discovered.Contains(c.ToString()))
        {
            sb.Append(c);
        }
        else
        {
            sb.Append('_');
        }
    }

    return sb.ToString();
}

HashSet<string> discovered = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

// The "secret" word
string word = "Hello world";

// How to add letters to the ones discovered
discovered.Add("l");

// The word ready to be shown
string convertWord = ConvertWord(word, discovered);

我们本可以用更少的字符来完成 ConvertWord,但今天已经足够了:-)

好的...我会给你一个例子,在 C# 4.0 中:

static string ConvertWord(string word, HashSet<string> discovered)
{
    return string.Concat(word.Select(p => discovered.Contains(p.ToString()) ? p : '_'));
}

关于c# - 将字符串显示为下划线但保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834129/

相关文章:

c# - 锁定 Windows Phone 模拟器

c# - 将照片 (CameraCaptureTask) 保存到隔离存储 - OutOfMemoryException

c# - 如何在 C# 中添加对 Photoshop CS4 COM 的引用

C# 使用 LINQ 查询更新字典 <string,string>

regex - 如何根据时间间隔获取这些错误/不匹配字符串

python - Python 中的参数化正则表达式

regex - 原子编辑器 : RegEx replace to uppercase/lowercase

windows-phone-7 - WP7-ListBox : Should I use Tap or SelectionChanged?

c# - 动态菜单系统的最佳方法

c# - 用 Ninject 拦截。无法加载 IProxyRequestFactory