c# - 根据特定字母从字符串中获取字母链

标签 c# notation chain letters polish

我有一个字符串,其中包含表示平面图(VLSI 布局)的波兰符号,它包含类似:“1234VHV56HV”的内容。 (仅供引用,这意味着:垂直分离 3 和 4,然后水平分离结果 & 2,然后垂直分离结果 & 1,水平分离 5 和 6,然后垂直分离前两个结果。)

假设字符串变量被称为:polishNotation。包含的字母只有 'V' 垂直或 'H' 水平。

我正在尝试应用一种名为:“模拟退火” 的算法来更改波兰语表示法,因此我想随机选择一个索引(当然小于 polishNotation.Length)和如果这个索引指向一个字母(“V”或“H”),我想得到包含它的字母链,然后将每个“V”更改为“H”并将每个“H”更改为“V”.. . 换句话说:补充链条!

  • 例如:假设 polishNotation = "1234VHV56HV"并且随机索引 = 5,因此结果为 "H"...我想检索 "VHV"并将其补足为:"1234HVH56HV"。
  • 另一个例子:假设 polishNotation = "1234VHV56HV"并且随机索引 = 9,所以结果是 "H"...我想检索 "HV"并将它补成:"1234VHV56VH"。
  • 另一个例子:假设 polishNotation = "1234VHV56HV"并且随机索引 = 6,所以结果是 "V"...我想检索 "VHV"并将它补成:"1234HVH56HV"。

我希望我说清楚了……有什么建议吗?我正在使用 C#.net

最佳答案

你可以尝试这样的事情。我敢打赌有一种方法可以用正则表达式来做到这一点,但我一时想不起来。

    string Complement(string floorPlan)
    {
        int index = rand.Next(floorPlan.Length); //get a random integer within array bounds

        if (floorPlan[index] != 'H' || floorPlan[index] != 'V') // if we didn't grab a letter, return
            return floorPlan;

        int start = index; //we'll need to find the start of the 'letter group'

        for (int i = index; i >= 0; i--) // work backwards through the string
            if (floorPlan[i] == 'H' || floorPlan[i] == 'V') // updating if we find another letter
                start = i;
            else // break when we don't
                break;            

        StringBuilder sb = new StringBuilder(floorPlan); // use a string builder for ease of char replacement

        for (int i = start; i < floorPlan.Length; i++) // using the start index, interate through
            if (floorPlan[i] == 'V') // and replace accordingly
                sb[i] = 'H';
            else if (floorPlan[i] == 'H')
                sb[i] = 'V';
            else // breaking when we encounter a number
                break;

        return sb.ToString();
    }

关于c# - 根据特定字母从字符串中获取字母链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17425369/

相关文章:

c# - Resharper - 生成相等成员包括基类成员

c# - 如何在程序关闭后运行操作?

c# - 使用C#隧道HTTP,HTTPS和DNS

java - 伪代码数组符号混淆

jq - jq 表示法 <function>/<number> 是什么意思?

events - Mootools:如何在补间或变形 FX 或其他事件结束后触发一个函数(或多个函数)?

c# - EF Core - 自引用实体

haskell - haskell 中的 ((->) t ) 是什么?

javascript - 如何在 JavaScript 中使用链而不应用反模式?

WiX 刻录引导运行不同的 InstallCommand 参数进行静默安装