将字符串值从AAA增加到AAB到AAC,依此类推

时间:2014-05-27 18:21:11

标签: c# algorithm

给定字符串AAB,如何返回字符串AAC?我已尝试在此答案中使用某些方法,但在尝试将int转换为char时出错,反之亦然。

public string GetNextPrefix(string prefixToIncrement)
{
    char[] digits = prefixToIncrement.ToCharArray();

    for (int i = previousPrefix.Length - 1; i >= 0; --i)
    {
        if (digits[i] == 'Z')
        {
            digits[i] = 'A';
        }
        else
        {
            digits[i] = digits[i] + 1;  //error here
            break;
        }
    }
    return new String(digits);
}

更新:Duh。有时我在这里发帖时,答案就在我发布时就出现了。错误是:

Cannot covert source type 'int' to target type 'char'

我通过将该行改为:

解决了这个问题
digits[i] = (char) (digits[i] + 1);

3 个答案:

答案 0 :(得分:5)

您可以转换为int,然后返回char:

digits[i] = (char)((int)digits[i] + 1);

更新

它也适用于不转换为int:

digits[i] = (char)(digits[i] + 1);

答案 1 :(得分:0)

public string GetNextPrefix(string prefix, string format = "000")
{
    const string Charset = "ABCDEF";

    //remove the ToUpper() if you want to expand the charset to contains both cases
    var values = prefix.ToUpper().Select(c => Charset.IndexOf(c));
    if (values.Any(v => v == -1))
        throw new Exception("Invalid Prefix : " + prefix);

    var value = values.Aggregate(0, (acc,v) => acc = acc * Charset.Length + v) + 1;
    var result = String.Empty;

    while(value != 0)
    {
        var remainder = value % Charset.Length;

        result = Charset[remainder] + result;
        value = (value - remainder) / Charset.Length;
    }

    return result.PadLeft(format.Length, Charset[0]);
}

答案 2 :(得分:0)

确实,这会导致类型冲突:

digits[i] = digits[i] + 1;

就像这样:

digits[i] += 1;

但这很好用:

digits[i]++;

谢谢你:Incrementation of char