【问题标题】:Add next character to each char in a string将下一个字符添加到字符串中的每个字符
【发布时间】:2017-07-14 07:19:00
【问题描述】:

我必须将它与 ASCII 表中的下一个字符一起返回,例如:

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

我尝试将字符串拆分为字符并对每个字符求和 1,但它给出了一个错误。

【问题讨论】:

  • 你能说明你面临的错误吗
  • 提示使用 toCharArray() 然后 stackoverflow.com/questions/1026220/… 然后 concat
  • 在提出问题时,您应该向我们展示您的代码并准确说明错误。事实上,我们绝对无法告诉您出了什么问题,因为我们看不到您的代码。即使您告诉我们错误是什么,我们也可以从中猜出您的代码是什么以及哪里出错了。因为虽然这个问题没有帮助回答(我们尽量不只是根据要求为人们编写代码)。
  • 这种类型的字符转换有几个硬边界和软边界。如果您的允许数据不包含某些UTF-16 code units,您可以保持算法简单并使用if (c >= '\uD7FF') throw new ArgumentOutOfRangeException(); 之类的东西来保护它

标签: c# string


【解决方案1】:

试试这个:

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'

【讨论】:

  • 谢谢你的朋友,这正是我正在寻找的
  • 您的包装中似乎存在某种语言的字母表假设。也许是英语。
  • char 可以隐式转换为 int,因此您可以通过 c + 1 删除额外的转换。
【解决方案2】:

试试这个:

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

【讨论】:

  • 在这里提到“ASCII”编码有点误导。 char 是一个 UTF-16 代码单元,它是 Unicode 字符集的几种编码之一。
猜你喜欢
  • 1970-01-01
  • 2020-06-12
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多