如何在C#中更改字符串修订格式?

时间:2016-09-27 05:29:50

标签: c#

至于我的要求,我想新更改字符串修订格式。基于以下格式。

E.g:
 ______________
|Test-A       |
|  ...        +
|Test-Z       | ==>IF Test-Z then Next time i need to create Revision "AA" 
|  ...        +
|Test-AA      |
| ...         +
|Test-AZ      |==>IF Test-AZ then Next time i need to create Revision "BA" 
| ...         +
|Test-BA      |
| ...         +
|Test-BZ      |==>IF Test-BZ then Next time i need to create Revision "CA" 
| ...         +
|Test-CA      |
| ...         +
|Test-CZ      |==>IF Test-CZ then Next time i need to create Revision "DA" 
+_____________+

E.g2 :

A,B ...... Z& AA,BB .... AZ然后我需要改变BA ... BB,BC .... BZ& CA,CB .... CZ。

请帮我解决这个任务。

2 个答案:

答案 0 :(得分:1)

我认为你需要两种方法来做到这一点: 1:一个String to Integer方法,它返回一个可以添加1的数字。 2:将数字转换回字符串的方法。

我目前在平板电脑上,所以这里只是一些未经测试的代码:

private int StringToInt(string version)
{
    int returnValue =0;
    // Iterate through the given string char by char and convert it to an integer
    // (A=65 in the ascii table, therefore we nned to substract it)
    for(int i=0; i<version.Length;i++)
    {
        // The alphabet has 26 chars so we just think of your version
        // as a base26 number and convert it to a base10 number.
        retunValue+=Math.Pow(26,i)*((int)version[version.Length-1-i]-65);
    }
    return returnValue;
}

private string IntToSting(int value)
{
    String returnValue=String.Empty;
    while(value /26>0)
    {
        // % is the modulo operator. eg if value was 27, value%26 == 1
        returnValue=((char)(value%26+65)).ToString()+returnValue;
        value-=value%26;
    }

    returnValue=((char)(value%26+65)).ToString() +returnValue;
}

请注意,这些方法仅适用于大写字母,并且它们不处理特殊情况,例如IntToString(0);

现在,您可以通过调用方法并在调用IntToString之前将StringToInteger的结果加1来简单地使用它。

version = IntToString(StringToInteger(version)+1);

答案 1 :(得分:1)

听起来像是家庭作业:

public class RevisionNumber
{
    private static readonly string[] _Representations = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
    private int _Value;

    public void Increment()
    {
        _Value++;
    }

    public override string ToString()
    {
        var result = String.Empty;
        var value = _Value;

        while (value >= _Representations.Length)
        {
            result = _Representations[(int)value % _Representations.Length] + result;
            value /= _Representations.Length;
            value--;
        }

        return _Representations[(int)value] + result;
    }
}

用法:

using System;

namespace ConsoleApplication
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var revision = new RevisionNumber();

            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(revision);
                revision.Increment();
            }

            Console.ReadKey();
        }
    }
}

相应的fiddle is here