How to find out next character alphabetically? - c#

How we can find out the next character of the entered one. For example, if I entered the character "b" then how do I get the answer "c"?

Try this:
char letter = 'c';
if (letter == 'z')
nextChar = 'a';
else if (letter == 'Z')
nextChar = 'A';
else
nextChar = (char)(((int)letter) + 1);
This way you have no trouble when the char is the last of the alphabet.

How about:
char first = 'c';
char nextChar = (char)((int) first + 1);

Note that a char will implicitly cast to an int. Here's a simplified solution:
char incrementCharacter(char input)
{
return (input == 'z'? 'a': (char)(input + 1));
}

Perhaps the simplest way is a little function and an array of the 26 chars. Then you can decide what you want to return for 'z'.

Convert the character to a number, increment the number and then convert back.
But consider what will happen for "z" or "รก" (Latin Small Leter A with Acute).

This Change value useful for Excel application to find previous column
public static string PrevExecelColumn( string s)
{
s = s.ToUpper();
char[] ac = s.ToCharArray();
int ln = ac.Length;
for (int i = ln - 1; i > -1; i--)
{
char c = ac[i];
if (c == 'A')
{
ac[i] = 'Z';
continue;
}
ac[i] = (char)(((int)ac[i]) - 1);
break;
}
s = new string(ac);
return s;
}

Try this :
public string GetNextAlphabetLetter(int indice) {
return ((char)('A' + indice)).ToString();
}

need to just add 1 in character you get next character.
It works on ASCII values.

Related

Issue with removing spaces from string in caesar cipher c#

I'm trying to make a Caesar cipher program, however I am unable to remove the spaces from the final encrypted output. I used:
if (letter == ' ')
continue;
However this seems to not be working and I can't identify what is causing the issue. I haven't been working with C# very long so it may potentially be a stupid error.
If I was to input the phrase with a shift of 7: "I need help" the following output would be pAullkAolsw with all spaces becoming uppercase A. The output I wish to have should be in the example: p ullk olsw.
Below is my full code:
using System;
class Program
{
static string Caesar(string value, int shift)
{
char[] buffer = value.ToCharArray();
for (int i = 0; i < buffer.Length; i++)
{
char letter = buffer[i];
letter = (char)(letter + shift);
if (letter == ' ')
continue;
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
buffer[i] = letter;
}
return new string(buffer);
}
static void Main()
{
Console.WriteLine("Enter text to encrypt: ");
string buffer = Console.ReadLine();
Console.WriteLine("Enter value of shift: ");
int shift = int.Parse(Console.ReadLine());
string final = Caesar(buffer, shift);
Console.WriteLine(final);
}
}
If you want to skip spaces you just have to check before you transform the letter variable:
char letter = buffer[i];
if (letter == ' ')
continue;
letter = (char)(letter + shift);
// ...
You should encrypt if and only if you know how to do it (i.e. if you have a a..z or A..Z character); in case you have different character (space, minus sign, quotation mark, whatever), just leave it intact:
using System.Linq;
...
static string Caesar(string value, int shift) {
//DONE: do not forget about validation
if (null == value)
return value; // or throw exception (ArgumentNullValue)
int n = 'z' - 'a' + 1;
// For each character in the value we have three cases:
// a..z letters - encrypt
// A..Z letters - encrypt
// other letters - leave intact
// "n + shift % n) % n" - let's support arbitrary shifts, e.g. 2017, -12345 etc.
return string.Concat(value
.Select(c =>
c >= 'a' && c <= 'z' ? (char) ('a' + (c - 'a' + n + shift % n) % n)
: c >= 'A' && c <= 'Z' ? (char) ('A' + (c - 'A' + n + shift % n) % n)
: c));
}
Test:
Console.Write(Caesar("Hello! It's a test for so called 'Caesar cipher'.", -2));
Outcome (please, notice that spaces, apostrophes, exclamation mark are left as they were):
Fcjjm! Gr'q y rcqr dmp qm ayjjcb 'Aycqyp agnfcp'.

Add next character to each char in a string

i've to return it with the next character in the ASCII table, example:
string tmp = "hello";
string modified = "ifmmp";
I've tried to split string into characters and sum 1 to each character but it gives out an error.
Try this out:
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)
}
}
Edit: I assumed adding one to all characters is cyclic, that is, adding one to 'z' will give an 'a'
Try this :
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
Create this method :
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;
}

Removing all non letter characters from a string in C#

I want to remove all non letter characters from a string. When I say all letters I mean anything that isn't in the alphabet, or an apostrophe. This is the code I have.
public static string RemoveBadChars(string word)
{
char[] chars = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
char c = word[i];
if ((int)c >= 65 && (int)c <= 90)
{
chars[i] = c;
}
else if ((int)c >= 97 && (int)c <= 122)
{
chars[i] = c;
}
else if ((int)c == 44)
{
chars[i] = c;
}
}
word = new string(chars);
return word;
}
It's close, but doesn't quite work. The problem is this:
[in]: "(the"
[out]: " the"
It gives me a space there instead of the "(". I want to remove the character entirely.
The Char class has a method that could help out. Use Char.IsLetter() to detect valid letters (and an additional check for the apostrophe), then pass the result to the string constructor:
var input = "(the;':";
var result = new string(input.Where(c => Char.IsLetter(c) || c == '\'').ToArray());
Output:
the'
You should use Regular Expression (Regex) instead.
public static string RemoveBadChars(string word)
{
Regex reg = new Regex("[^a-zA-Z']");
return reg.Replace(word, string.Empty);
}
If you don't want to replace spaces:
Regex reg = new Regex("[^a-zA-Z' ]");
A regular expression would be better as this is pretty inefficient, but to answer your question, the problem with your code is that you should use a different variable other than i inside your for loop. So, something like this:
public static string RemoveBadChars(string word)
{
char[] chars = new char[word.Length];
int myindex=0;
for (int i = 0; i < word.Length; i++)
{
char c = word[i];
if ((int)c >= 65 && (int)c <= 90)
{
chars[myindex] = c;
myindex++;
}
else if ((int)c >= 97 && (int)c <= 122)
{
chars[myindex] = c;
myindex++;
}
else if ((int)c == 44)
{
chars[myindex] = c;
myindex++;
}
}
word = new string(chars);
return word;
}
private static Regex badChars = new Regex("[^A-Za-z']");
public static string RemoveBadChars(string word)
{
return badChars.Replace(word, "");
}
This creates a Regular Expression that consists of a character class (enclosed in square brackets) that looks for anything that is not (the leading ^ inside the character class) A-Z, a-z, or '. It then defines a function that replaces anything that matches the expression with an empty string.
This is the working answer, he says he want to remove none-letters chars
public static string RemoveNoneLetterChars(string word)
{
Regex reg = new Regex(#"\W");
return reg.Replace(word, " "); // or return reg.Replace(word, String.Empty);
}
word.Aggregate(new StringBuilder(word.Length), (acc, c) => acc.Append(Char.IsLetter(c) ? c.ToString() : "")).ToString();
Or you can substitute whatever function in place of IsLetter.

See if a string contains a char and write it out

I'm a beginner at this and hoping someone can help me.
What I am trying do is check if the character in char b exists in string s. If it exists, it should write the letter out to the char array at the right index number. If not, then it should write a - instead. But this keeps resetting for me every new instance of char b. Any ideas?
public static void test(char[] h, char b, string s)
{
for (int i = 0; i < s.Length; i++)
{
if (s[i] == b)
{
h[i] = b;
Console.Write(h[i]);
}
if (s[i] != b)
{
h[i] = '-';
Console.Write(h[i]);
}
}
}
.Contains() method
Try the string.Contains method that would work for you.
someString.Contains('c'); // where c can be any character. returns a bool value
http://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx
.IndexOf() method
You can try getting the character at the indexNumber of the string too.
int index = IndexOf("String here"); // zero based index number... returns int
The above mentioed code is a single line code to find the character.
http://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx
Just for sake of help
I think you want to search for each character in the available String. Few days ago, Jon Skeet, told me this one
char characterToFind = 'r';
string s = "Hello world!";
int index = 0; // because foreach won't use any int i = 0 method
foreach (char c in s) { // foreach character in the string
// read the character and post the output
if(c == characterToFind) {
Console.Write("Character found at: " + index.ToString());
}
index++; // increment
}
You can simply do the following:
string str = "hello world";
str.Contains('h');
You can also use:
string.IndexOfAny(b) >= 0;
It will give you the index of the char that you can store in your array.
You can use the str.IndexOf(String char) method.
You can simplify your code to this:
for (int i = 0; i < s.Length; i++)
{
if(s[i] == b)
{
h[i] = b;
}
else
{
h[i] = '-';
}
Console.Write(h[i]);
}
(..and actually simplify it further with the ternary operator ?:, but let's keep things simple). Running it with this as input:
var h = new char[16];
test(h, 'p', "purple people");
Produces this input:
p--p---p--p--
..which I think is what you're after.

Remove a char from a String

I'm looking for a method which can remove a character of a string.
for example I have " 3*X^4" and I want to remove characters '*' & '^' then the string would be like this "3X4" .
Maybe:
string s = Regex.Replace(input, "[*^]", "");
var s = "3*X^4";
var simplified = s.Replace("*", "").Replace("^", "");
// simplified is now "3X4"
try this..it will remove all special character from string
public static string RemoveSpecialCharacters(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
|| c == '.' || c == '_')
{
sb.Append(c);
}
}
return sb.ToString();
}
Another solution would be extracting the unwanted characters manually - this might be slightly more performant than repeatedly calling string.Replace especially for larger numbers of unwanted characters:
StringBuilder result = new StringBuilder(input.Length);
foreach (char ch in input) {
switch (ch) {
case '*':
case '^':
break;
default:
result.Append(ch);
break;
}
}
string s = result.ToString();
Or maybe extracting is the wrong word: Rather, you copy all characters except for those that you don't want.
Try this: String.Replace(Old String, New String)
string S = "3*X^4";
string str = S.Replace("*","").Replace("^","");

Categories