在c#中获取下一个字符 [英] Get Next Character in c#

查看:71
本文介绍了在c#中获取下一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#Win中获得下一个角色。形成。如果



i有 A 它应该给 B

i有 a 它应该给 b

i 8 它应该给 9

i有它应该给



如果到达ASCII的最后一个字符给出消息完成







提前致谢



[注意:如果我尝试

How to Get Next Character in C# Win. Form. Like if

i have A it should give B
i have a it should give b
i have 8 it should give 9
i have ! it should give "

and if reaches the last character of ASCII gives message "Done".



Thanks in advance

[Note: if i try

nextChar = ((char)(ASCIICode + 1));

ASCIICode达到255以上它没有给出任何错误并继续显示结果。为什么会这样?]

and ASCIICode reaches above 255 it doesn't give any error and keeps on displaying the result. Why this is so?]

推荐答案

using System;

public class Program
{
    public static void Main()
    {
        //char c = (char)127; // last ascii character
        char c = 'A';

        if ((int)c == 127) // check for last ascii character
        {
            Console.WriteLine("Done");
        }
        else
        {
            char result = getNextChar(c);

            Console.WriteLine("I have " + c + " it should give " + result);
        }
    }

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


除了解决方案1之外,它还取决于ASCII的最后一个字符的含义 - 这可能是取决于使用的代码页。讨论此处 [ ^ ]比我更好解释。



这个小功能将勇敢地尝试找到下一个可打印字符
Further to solution 1 it also depends on what you mean by "the last character of ASCII" - this may depend on the Code Page in use. A discussion here[^] explains it better than me.

This little function will valiantly try to find the next printable character
private char NextLetter(char letterIn)
{
    int a = (int)letterIn + 1;

    char ret;
    if (char.IsLetterOrDigit((char)a) || char.IsSymbol((char)a) || char.IsPunctuation((char)a))
        ret = ((char)a);
    else
    {
         ret = NextLetter((char)a);
    }
    return ret;
}



从一个太大的循环调用它会跳过不可打印的东西...即输出从!开始

例如


Calling it from a too-large loop skips the non-printable stuff ... i.e. output starts at "!"
E.g.

for (int i = 0; i < 300; i++)
    Debug.Print(NextLetter((char)i).ToString());


尝试以下方法 -

Try the following -
if (letter == 'z')
    nextChar = 'a';
else if (letter == 'Z')
    nextChar = 'A';
else
    nextChar = (char)(((integer) letter) + 1);


这篇关于在c#中获取下一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆