Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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));
and ASCIICode reaches above 255 it doesn't give any error and keeps on displaying the result. Why this is so?]
Posted
Updated 8-Mar-14 18:06pm
v2

C#
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;
    }
}
 
Share this answer
 
Comments
agent_kruger 16-May-14 9:32am    
no sir, you limited to the number 127 and i want it till 255.
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
C#
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.
C#
for (int i = 0; i < 300; i++)
    Debug.Print(NextLetter((char)i).ToString());
 
Share this answer
 
Try the following -
C#
if (letter == 'z')
    nextChar = 'a';
else if (letter == 'Z')
    nextChar = 'A';
else
    nextChar = (char)(((integer) letter) + 1);
 
Share this answer
 
Comments
agent_kruger 9-Mar-14 0:01am    
sir, i searched through the article where you picked the code from but here i want after last character of ASCII gives message "Done". How to do the last part?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900