在字符串中为每个字符添加下一个字符

时间:2017-02-23 17:05:42

标签: c# string

我将使用ASCII表中的下一个字符返回它,例如:

string tmp = "hello";
string modified = "ifmmp";

我试图将字符串拆分为字符,并将每个字符加1,但它会发出错误。

2 个答案:

答案 0 :(得分:3)

试试这个:

public string NextCharString(string str)
{
    string result = "";
    foreach(var c in str)
    {
        if (c=='z') result += 'a';
        else if (c == 'Z') result += 'A';
        else result += (char)(((int)c) + 1)
    }
}

编辑:我假设在所有字符中添加一个是循环的,也就是说,在'z'中添加一个将给出'a'

答案 1 :(得分:0)

试试这个:

            string tmp = "hello";
            string modified = "";
            for (int i = 0; i < tmp.Length; i++)
            {
                char c = getNextChar(tmp[i]);
                modified += c;
            }

         // 'modified' will be your desired output

创建此方法:

       private static char getNextChar(char c)
        {

            // convert char to ascii
            int ascii = (int)c;
            // get the next ascii
            int nextAscii = ascii + 1;
            // convert ascii to char
            char nextChar = (char)nextAscii;
            return nextChar;
        }