根据特定字母从字符串中获取字母串

时间:2013-07-02 12:13:59

标签: c# notation chain letters polish

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

假设调用字符串变量: polishNotation 。包含的字母只有'V'表示垂直,'H'表示水平。

我正在尝试应用一种叫做“Simulated Annealing”的算法来改变波兰表示法,所以我想随机选择一个索引(当然小于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

1 个答案:

答案 0 :(得分:0)

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

    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();
    }