How to save output to text file - c#

I've made a program where I can decrypt some encrypted text, it does this by reading a text file and shifting the text one letter at a time, and it does this 26 times, but I can't get it to save and write the output to a text file, this is my code below, I would appreciate any help if possible, thank you
using System;
using System.IO;
namespace Assignment1
{
class MainClass
{
public static void Main(string[] args)
{
//Writing to the screen
Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");
string userValue = Console.ReadLine();
//User's value is set to userValue
// if the user types "y", activate the decryption method
if (userValue.ToLower() == "y")
{
decryption();
}
// if the user types in "n", write "Goodbye" and close the program
if (userValue.ToLower() == "n")
{
Console.WriteLine("Goodbye");
Console.ReadLine();
Environment.Exit(0);
//Environment.exit closes the program
}
}
//Decryption method
public static void decryption()
{
//ShiftLine is equal to new char
char[] ShiftLine = new char[0];
//If the shift is smaller or equal to 25, continue to shift one at a time
for (int shift = 1; shift <= 26; shift++)
{
//This reads the encryptefd text file into the program
string textFile = #"C:\Users\Anthony\Desktop\caesarShiftEncoded.txt";
//The string "test" reads all the lines of the textFile
string[] text = File.ReadAllLines(textFile);
foreach (string line in text)
{
//Sets currentLetter to 0
int CurrentLetter = 0;
int[] ShiftNumbers = new int[line.Length];
ShiftLine = new char[line.Length];
foreach (char letter in line)
{
ShiftNumbers[CurrentLetter] = ConvertLetterToNumber(letter);
ShiftNumbers[CurrentLetter] = ShiftCipher(ShiftNumbers[CurrentLetter], shift);
ShiftLine[CurrentLetter] = ConvertNumberToLetter(ShiftNumbers[CurrentLetter]);
CurrentLetter++;
}
Console.WriteLine(string.Join("", ShiftLine));
}
//Console.WriteLine (textFile.Length);
Console.WriteLine("This is Shift No: {0}", shift);
}
Console.WriteLine("Which Shift Would You Like To Write to a Text File: ");
string userNumber = Console.ReadLine();
if (userNumber.ToLower() == "1 =< 26")
{
using (StreamWriter text = new StreamWriter("TextWrittenFile.txt"))
{
foreach (char line in ShiftLine)
{
text.WriteLine(ShiftLine);
File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", ShiftLine);
}
}
}
}
public static int ShiftCipher(int Number, int Shift)
{
if (Number == 27)
{
return 27;
}
else if (Number == 28)
{
return 28;
}
else if (Number > Shift)
{
return (Number - Shift);
}
else if (Number <= Shift)
{
return (26 + (Number - Shift));
}
else
{
return 0;
}
}
public static int ConvertLetterToNumber(char Letter)
{
switch (Char.ToLower(Letter))
{
case 'a':
return 1;
case 'b':
return 2;
case 'c':
return 3;
case 'd':
return 4;
case 'e':
return 5;
case 'f':
return 6;
case 'g':
return 7;
case 'h':
return 8;
case 'i':
return 9;
case 'j':
return 10;
case 'k':
return 11;
case 'l':
return 12;
case 'm':
return 13;
case 'n':
return 14;
case 'o':
return 15;
case 'p':
return 16;
case 'q':
return 17;
case 'r':
return 18;
case 's':
return 19;
case 't':
return 20;
case 'u':
return 21;
case 'v':
return 22;
case 'w':
return 23;
case 'x':
return 24;
case 'y':
return 25;
case 'z':
return 26;
case ' ':
return 27;
default:
return 0;
}
}
public static char ConvertNumberToLetter(int Number)
{
switch (Number)
{
case 1:
return 'a';
case 2:
return 'b';
case 3:
return 'c';
case 4:
return 'd';
case 5:
return 'e';
case 6:
return 'f';
case 7:
return 'g';
case 8:
return 'h';
case 9:
return 'i';
case 10:
return 'j';
case 11:
return 'k';
case 12:
return 'l';
case 13:
return 'm';
case 14:
return 'n';
case 15:
return 'o';
case 16:
return 'p';
case 17:
return 'q';
case 18:
return 'r';
case 19:
return 's';
case 20:
return 't';
case 21:
return 'u';
case 22:
return 'v';
case 23:
return 'w';
case 24:
return 'x';
case 25:
return 'y';
case 26:
return 'z';
case 27:
return ' ';
default:
return '0';
}
}
}
}

As your ShiftLine seems to be an array of chars it could be as simple as that:
File.WriteAllText("C:\Users\Anthony\Desktop\DecryptedText.txt", new string(ShiftLine));
(instead of your loop [btw: Your loop overwrites the file on any turn...])

Actually there are a few things you could improve.
If the user shall only be able to press y or n, you could use the Console.ReadKey() method instead of letting the user input a complete line of text. By using the overloaded method and specifying true as argument, you won't even see the pressed key on written into the console window (Console.ReadKey(true)).
So you could exchange the current if statements with switch (Console.ReadKey(true).Key) and build cases like case ConsoleKey.Y:
So the Main method would look something like that:
public static void Main(string[] args)
{
//Writing to the screen
Console.WriteLine("Welcome to the Ceaser Cipher Shift Program");
Console.WriteLine("Would You Like to Decrypt a File (y for yes/n for no)");
switch (Console.ReadKey(true).Key)
{
// if the user types "y", activate the decryption method
case ConsoleKey.Y:
decryption();
break;
// if the user types in "n", write "Goodbye" and close the program
case ConsoleKey.N:
default:
Console.WriteLine("Goodbye");
Environment.Exit(0);
break;
}
}
I guess the next thing you want to do is using Caesar cipher for encrypting/decrypting data.
Therefore you "just" need to shift every character and this can be done much easier than writing switch-case statements like you did. The idea behind this type of encryption is, that you take one character and replace it with another one which is offset characters away. Decrypting goes the other way.
So it would be much easier building one method that has the ability to do exactly that for a specified text.
There are two special cases you need to consider: What happens if the value you are looking at is on the lower boundary and you substract the offset (meaning, the "new" value would be lower than zero). The second one represents the same situation on the upper boundary.
These sitations can be resolved using either if statements or possibly easier by just looking at the rest of the division with the maximum value range. (text[i] + offset) % NumberOfPossibleCharacters should do the trick.
Knowing this you can easily build a method like the following one (where I have assumed, that there is no character with a value greater than 127):
static string Encrypt(string data, int offset)
{
string result = string.Empty;
for (int i = 0; i < data.Length; i++)
{
// Add the offset to the current character and just take the
// rest of the division by 127. Afterwards cast it back to a character
// (because it will be a number due to + and %)
result += (char)((data[i] + offset) % 127);
}
return result;
}
Be advised, that string operations like += will cause the creation of a new string each time so it is not a good example from an (memory)performance point of view. There is the better way of using the StringBuilder class.
I hope this hint's you in a better way of solving your homework ;-)

Related

How can this C project to change vewels to $ be translated into C#?

Not a problem as much as a curiosity. I came about this old post yesterday and started playing with it in C#. Heres the original post form 2011(How to change vowels in a string to a symbol?).
I changed some of the code along with a counter to count the total letters in the word. I am stuck on the if statement. I know this program may not have any real world purpose, but I'm trying to learn C# string manipulation.
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i < wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
theLetter = theLetter.ToLower();
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
string rebuilt = new string(wordArray);
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
Console.ReadLine();
I just want to change the vowels to $ or any other letter or symbol and count the digits in the word.
The first problem with the C program in the post you linked to is that it only changes the lower-case vowels to '$', not the upper-case ones. The second problem is that strings in C# are immutable, and you already worked around this by changing the word into an array, modifying that, and creating a new string from the modified array.
A method to convert all vowels to '$' might look like this:
public static string VowelsToSymbol(string input)
{
if (string.IsNullOrWhiteSpace(input)) return input;
var work = new char[input.Length];
for (int i = 0; i < work.Length; i++)
{
var c = input[i];
switch (c)
{
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
work[i] = '$'; break;
default:
work[i] = c; break;
}
}
return new string(work);
}
Slightly less efficient but much better at showing the intent (what is being done) instead of the mechanics (how is it done):
private static char OneVowelToSymbol(char c)
{
switch (c)
{
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
return '$';
default:
return c;
}
}
public static string VowelsToSymbolLinq(string input)
{
return string.IsNullOrWhiteSpace(input) ? input :
new string(input.Select(OneVowelToSymbol).ToArray());
}
If you want to allow for accented characters (or whatever else may count for a vowel in some language other than English), things get ugly quite quickly, and you may be better off using a different method (search the internet for '".NET" isvowel' to find examples).

Using Case Break to convert string to int C# [duplicate]

This question already has answers here:
Unreachable code detected in case statement
(14 answers)
Closed 7 years ago.
I'm trying to convert string to int. I think I have it right, but what else do I need to do? Under "Break" I get a green line saying "unreachable code detected". Also, what do I tell it to return? I put a random number after return, because I have blanked on what I should ask it to return.
namespace BattleShip.UI
{
class TranslateNumberToLetter
{
public int NumberToLetter(string Letter)
{
switch (Letter)
{
case "A":return 1;
break;
case "B": return 2;
break;
case "C": return 3;
break;
case "D": return 4;
break;
case "E": return 5;
break;
case "F": return 6;
break;
case "G": return 7;
break;
case "H": return 8;
break;
case "I": return 9;
break;
case "J": return 10;
break;
default: return -100;
}
}
}
}
public int NumberToLetter(string Letter)
{
if ("ABCEDFGHIJ".Contains(Letter))
return "ABCEDFGHIJ".IndexOf(Letter) + 1;
return -100;
}

Generate Sequential Passwords in C#

I have been trying to generate passwords sequentially in C# (aaaa, aaab, aaac, ... abcd, abce) for a hash cracker (for white-hat purposes). However, I'm not sure how to do that.
Right now I have a char array, the last element of which is being incremented by a switch:
switch (character) {
case ('0'):
character = '1';
break;
case ('1'):
character = '2';
break;
case ('2'):
character = '3';
break;
case ('3'):
character = '4';
break;
case ('4'):
character = '5';
break;
case ('5'):
character = '6';
break;
case ('6'):
character = '7';
break;
case ('7'):
character = '8';
break;
case ('8'):
character = '9';
break;
case ('9'):
character = 'a';
break;
case ('a'):
character = 'b';
break;
case ('b'):
character = 'c';
break;
case ('c'):
character = 'd';
break;
case ('d'):
character = 'e';
break;
case ('e'):
character = 'f';
break;
case ('f'):
character = 'g';
break;
case ('g'):
character = 'h';
break;
case ('h'):
character = 'i';
break;
case ('i'):
character = 'j';
break;
case ('j'):
character = 'k';
break;
case ('k'):
character = 'l';
break;
case ('l'):
character = 'm';
break;
case ('m'):
character = 'n';
break;
case ('n'):
character = 'o';
break;
case ('o'):
character = 'p';
break;
case ('p'):
character = 'q';
break;
case ('q'):
character = 'r';
break;
case ('r'):
character = 's';
break;
case ('s'):
character = 't';
break;
case ('t'):
character = 'u';
break;
case ('u'):
character = 'v';
break;
case ('v'):
character = 'w';
break;
case ('w'):
character = 'x';
break;
case ('x'):
character = 'y';
break;
case ('y'):
character = 'z';
break;
case ('z'):
character = 'A';
break;
case ('A'):
character = 'B';
break;
case ('B'):
character = 'C';
break;
case ('C'):
character = 'D';
break;
case ('D'):
character = 'E';
break;
case ('E'):
character = 'F';
break;
case ('F'):
character = 'G';
break;
case ('G'):
character = 'H';
break;
case ('H'):
character = 'I';
break;
case ('I'):
character = 'J';
break;
case ('J'):
character = 'K';
break;
case ('K'):
character = 'L';
break;
case ('L'):
character = 'M';
break;
case ('M'):
character = 'N';
break;
case ('N'):
character = 'O';
break;
case ('O'):
character = 'P';
break;
case ('P'):
character = 'Q';
break;
case ('Q'):
character = 'R';
break;
case ('R'):
character = 'S';
break;
case ('S'):
character = 'T';
break;
case ('T'):
character = 'U';
break;
case ('U'):
character = 'V';
break;
case ('V'):
character = 'W';
break;
case ('W'):
character = 'X';
break;
case ('X'):
character = 'Y';
break;
case ('Y'):
character = 'Z';
break;
case ('Z'):
character = '#';
break;
case ('#'):
character = '%';
break;
case ('%'):
character = '/';
break;
case ('/'):
character = '\\';
break;
case ('\\'):
character = '\'';
break;
case ('\''):
character = '!';
break;
case ('!'):
character = '$';
break;
case ('$'):
character = '#';
break;
case ('#'):
character = '^';
break;
case ('^'):
character = '?';
break;
case ('?'):
character = ':';
break;
case (':'):
character = ',';
break;
case (','):
character = '(';
break;
case ('('):
character = ')';
break;
case (')'):
character = '[';
break;
case ('['):
character = ']';
break;
case (']'):
character = '{';
break;
case ('{'):
character = '}';
break;
case ('}'):
character = '-';
break;
case ('-'):
character = '_';
break;
case ('_'):
character = '+';
break;
case ('+'):
character = '=';
break;
case ('='):
character = '0';
break;
prev = true;
default:
character = '0';
break;
}
However, when that element reaches 0 again, I need to increment the previous digit of the password and if that digit also reaches 0, I need to increment the previous digit from that one, and so on.
Also, since this is a hash cracker, it needs to be fast. Any suggestions?
My first answer wouldn't give you quite what you want. This will:
Create a string that defines your alphabet:
const string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
Then initialize an int array with all -1, as long as your longest password. This one will do up to 8 characters:
int[] pwArray = new int[] {-1, -1, -1, -1, -1, -1, -1, -1};
Then run a loop:
for (int i = 0; i < Whatever; ++i)
{
string password = ToPasswordString(pwArray, Alphabet);
// do something with the password
}
string ToPasswordString(int[] pass, string alphabet)
{
for (int i = pass.Length-1; i > 0; --i)
{
pass[i]++;
if (pass[i] < alphabet.Length)
{
break;
}
pass[i] = 0;
}
var sb = new StringBuilder();
for (int i = 0; i < pass.Length; ++i)
{
if (pass[i] >= 0)
sb.Append(alphabet[pass[i]]);
}
return sb.ToString();
}
The key here is that we don't modify password characters. Rather, we modify indexes into the character array.
Granted, this won't be as fast as some other methods (passwords per second), but your program's speed is limited by how fast the site you're hacking can respond to login tries. The amount of time you spend generating passwords is irrelevant when compared to that.
Instead of a complicated and extremely large switch statement why not just directly map int values to char.
for (int i = 0; i < (int)Char.MaxValue; i++) {
char c = (char)i;
...
}
This would allow you to build up brute force password generator pretty easily.
You could use ascii code, for sample:
public char GetNextChar(char c)
{
return (char)(((int)c) + 1);
}
Would be a nice extension, for sample:
public static class Extensions
{
public static char GetNextChar(this char c)
{
return (char)(((int)c) + 1);
}
}
and using it:
character = character.GetNextChar();
Something like this should work.
char[] currPassword = new char[] { (char)65, (char)65, (char)65, (char)65, (char)65 }; //65 = A
const int Z = 90;
const int A = 65;
void Main()
{
while(true)
{
string curr = new string(currPassword);
Next();
}
}
public void Next()
{
int currIndex = currPassword.Length -1;
bool done = false;
do
{
currPassword[currIndex]++;
if(currPassword[currIndex] > Z && currIndex >= 0)
{
currPassword[currIndex] = (char)A;
currIndex--;
}
else
{
done = true;
}
}while(!done);
}
LINQLIB contains methods to compute all permutations or combinations. You could use it instead although the order might not be exactly as you describe in your question.
Another different approach:
static void Main(string[] args)
{
string charSet = "0123456789!##$%^&*";
string password = "20#";
StringBuilder start = new StringBuilder("0");
int j = 0;
int z = 0;
while (start.ToString() != password)
{
start[z] = charSet[j++];
Console.WriteLine(start);
if (j == charSet.Length)
{
if (start.ToString().Where(c => c == charSet[charSet.Length - 1]).Count() == start.ToString().Length)
{
start.Append("0");
for (int t = 0; t < start.Length; t++)
{
start[t] = '0';
}
z++;
}
else
{
for (int t = start.Length - 2; t >= 0; t--)
{
if (charSet.IndexOf(start[t]) == charSet.Length - 1)
{
start[t] = '0';
}
else
{
start[t] = charSet[charSet.IndexOf(start[t]) + 1];
break;
}
}
}
j = 0;
}
}
}
Just treat each of your password entries as numbers, its base being the number of characters present in the initial Dictionary. Whenever you reach a maximum in a given position, you 'carry over' to the next 'digit'.
This small class will return all possible combinations, given:
an initial character dictionary
a minimum password size
a maximum password size
Just keep in mind that sequences like that get EXTREMELY large very fast, depending on the initial dictionary size. For example, the following code with default values (minChar=2,MaxChar=4) generates 866495 entries.
public class Sequencer
{
public string characterDictionary = "0123456789";
//public string characterDictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[];',./`~!##$%^&*()_+{}|:\"<>?|\\";
public int minCharCount = 2;
public int maxCharCount = 4;
private List<string> _sequence;
public List<string> GetSequence()
{
_sequence = new List<string>();
for (int i = minCharCount; i < (maxCharCount + 1); i++)
RenderCombinations(i);
return _sequence;
}
private void RenderCombinations(int charCount)
{
int _dictSize = characterDictionary.Length;
int[] _containerMatrix = new int[charCount];
char[] _splitDict = characterDictionary.ToCharArray();
bool _maxReached = false;
do
{
string _currentCombination = "";
for (int i = 0; i < charCount; i++)
_currentCombination += _splitDict[_containerMatrix[i]];
_sequence.Add(_currentCombination);
// Let the shifting begin!
bool _mustCarry = false;
int _carryIndex = 0;
do
{
_mustCarry = false;
if (_carryIndex == _containerMatrix.Length)
{
_maxReached = true;
break;
}
_containerMatrix[_carryIndex]++;
if (_containerMatrix[_carryIndex] == _dictSize)
{
_mustCarry = true;
_containerMatrix[_carryIndex] = 0;
}
_carryIndex++;
if (_carryIndex > charCount)
{
_mustCarry = false;
_maxReached = true;
}
} while (_mustCarry);
} while (!_maxReached);
}
}

Converting values with Arabic numbers

The problem states "Write a program that accepts a 10-digit telephone number that may contain one or more alphabetic characters. Display the corresponding number using numerals...etc"
ABC:2 through WXYZ:9
This chapter teaches about loops but I found myself really lost at this problem. I completed the code but I think it sucks...
My question: Is there a better way to shorten this code up? And I only figured to use the c# keyword case, is there another way?
EDIT: Arabic as in you could type in 1800WALLTO and it will give you 1800925586
ALSO I am not asking for a code that doesn't work, this does EXACTLY what I want and asked it to do. I am just asking for any advise or input on how to make it better. I really wanted to know a way to do it without switch and case break etc...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 0;
char userInput = ' ';
string inputString = "",
outputString = "";
Console.WriteLine("Enter the digits from the phone number");
do
{
userInput = Console.ReadKey(false).KeyChar;
inputString += userInput;
if (Char.IsLetter(userInput))
userInput = userInput.ToString().ToUpper().ToCharArray()[0];
switch (userInput)
{
case '1':
outputString += '1';
x++;
break;
case '2':
case 'A':
case 'B':
case 'C':
outputString += '2';
x++;
break;
case '3':
case 'D':
case 'E':
case 'F':
outputString += '3';
x++;
break;
case '4':
case 'G':
case 'H':
case 'I':
outputString += '4';
x++;
break;
case '5':
case 'J':
case 'K':
case 'L':
outputString += '5';
x++;
break;
case '6':
case 'M':
case 'N':
case 'O':
outputString += '6';
x++;
break;
case '7':
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += '7';
x++;
break;
case '8':
case 'T':
case 'U':
case 'V':
outputString += '8';
x++;
break;
case '9':
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += '9';
x++;
break;
case '0':
outputString += '0';
x++;
break;
default:
Console.WriteLine("You entered an incorrect value-Try again");
x--;
break;
}
}
while (x < 10);
Console.WriteLine("\nYou entered {0}", inputString);
Console.WriteLine("Your number is {0}", outputString);
}
}
}
Use a System.Collections.Generic.Dictionary where the dictionary keys are the characters A-Z and 0-9 and the values are the corresponding numbers:
var lookup = Dictionary<char, int> {
{'A',2},
{'B',2},
// etc...
{'Z', 9},
{'1':1},
{'2':2}
// etc... include the numerals so you don't have to converts some things to char not the rest...
};
// to lookup a character:
char item = 'A';
int number = lookup['A'];
To decode an phone number just split it into an array of char's and look them up one after the other
List<int> digits = new List<int>();
foreach (char c in inputString)
{
digits.Add(lookup[c]);
}
Im sure somebody will post a 1-liner using LINQ as well, but this is the vanilla version.
Using a string look up would shorten the code:--
String decode "--------------------------------01234567890------2223334445556667778889999---------------------------------"; //256 char string
numout = decode.substring((int) Char.GetNumericValue(userinput),1);
But it would be a lot less efficient than using a "case" statement. Less code does not mean less cpu.

Need to read one character at time until 10 characters reached

I am working on a homework assignment, beginning C#.
Have to accept input from user:
phone number with numbers or characters
then return only the numeric version of number.
My program takes input and returns value, but does not end when 10 characters have been entered.
You can enter as many characters as you want, then when enter is pressed it only displays first 10.
It also does not test the cases after each character entered. Seems to do at the end.
I would like to have each character tested after input and then once ten characters have been entered
the program display results.
I hope I am giving enough info. I am pretty stressed about this.
It is due tomorrow and I have a few other programs to do yet.
Any help would be greatly appreciated.
My code:
Console.Write("Please enter your phone number: ");
do
{
int temp = Console.Read();
input = Convert.ToChar(temp);
//int tempInput = Convert.ToString(tempInput);
switch (input)
{
case '0':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
counter--;
break;
// { other cases }
default:
// if input does not match cases then loop returns to
// request new input
Display.Error(input.ToString());
Console.Write(alphaNumericPhoneNumber);
//Display.Continue();
//Console.Clear();
input = ' ';
break;
}
}
while (numericPhoneNumber.Length < 0);
return numericPhoneNumber;
}
The documentation for the Console.Read() method explains the described behavior.
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. [...] Subsequent calls to the Read method retrieve your input one character at a time.
If you want to process the characters as they arrive, you may use the KeyAvailableand ReadKey methods as demonstrated in the documentation. The example is available in 5 .NET languages, including C#.
Basically you need to use Console.ReadKey() instead of Console.Read() as the latter expects a \n from an ENTER press to return and the former returns immediately when key is pressed.
class Program
{
static void Main(string[] args)
{
ReadPhone();
Console.ReadLine();
}
private static void ReadPhone()
{
var numericPhoneNumber = string.Empty;
Console.Write("Please enter your phone number: ");
do
{
var keyInfo= Console.ReadKey();
if (char.IsDigit(keyInfo.KeyChar))
{
numericPhoneNumber += keyInfo.KeyChar;
}
else
{
Console.WriteLine();
Console.WriteLine("Please enter numeric numbers only");
}
}
while (numericPhoneNumber.Length <= 10);
Console.WriteLine("Phone Number: {0}", numericPhoneNumber);
}
}
static void Main(string[] args)
{
int i=0;
string str=String.Empty;
Char c;
Console.WriteLine("Enter number:");
while (i < 10)
{
if (char.IsDigit(c = Console.ReadKey().KeyChar))
{
str += c;
i++;
}
}
Console.WriteLine("str: "+str);
}
Thanks to everyone for your help.
I ended up using the readkey to evaluate each character and assign its respective numerical value as per the telephone keypad.
I don't think that I was very clear about it in my original post... little stressed about it at the time... spent to long on this question.
The replies to this post showed some pretty clean code. I hope to get to that level soon.
I will show what I ended up doing, just incase someone in interested.
Thanks again for your help.
class Request
{
public static void GetPhoneNumber(out string UserInput, out string ConvertedString)
{
// create instance of ConsoleKeyInfo
ConsoleKeyInfo cki = new ConsoleKeyInfo();
string alphaNumericPhoneNumber = " ";
string numericPhoneNumber = " ";
char input = ' ';
Console.Write("Please enter your phone number: ");
// perform a do... while loop to read 10 characters of input
do
{
cki = Console.ReadKey();
input = cki.KeyChar;
switch (char.ToUpper(input))
{
case '0':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
break;
case '1':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
break;
case 'A':
case 'B':
case 'C':
case '2':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "2";
break;
case 'D':
case 'E':
case 'F':
case '3':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "3";
break;
case 'G':
case 'H':
case 'I':
case '4':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "4";
break;
case 'J':
case 'K':
case 'L':
case '5':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "5";
break;
case 'M':
case 'N':
case 'O':
case '6':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
case '7':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "7";
break;
case 'T':
case 'U':
case 'V':
case '8':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
case '9':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "9";
break;
default:
// if input does not match cases then loop returns to
// request new input
Console.Clear();
Display.Error(input.ToString());
// display for user to continue... displays valid numbers so far
Console.Write("Continue with phone number: " + alphaNumericPhoneNumber);
input = ' '; // returns blank character and not added to strings so not counted
break;
}
}
while (numericPhoneNumber.Length < 11); // counts until string has 10 digits
UserInput = alphaNumericPhoneNumber;
ConvertedString = numericPhoneNumber;
}
}
Ok, not so sure about helping you with your homework. I used to sell my assignments to other kids when I was studying, so I guess I can't take the moral high ground here.
Here's a solution, but make sure you do some googling and understand how it works.
// Initialise the result to nothing.
string result = string.Empty;
do
{
// Prompt for input.
Console.WriteLine("Please enter your 10-digit phone number: ");
// Read the response.
string input = Console.ReadLine();
// Replace any characters that are not numbers with the empty string (remove them).
result = System.Text.RegularExpressions.Regex.Replace(input, "[^0-9]", string.Empty);
}
while (result.Length != 10);
// Do something with the result.
Console.WriteLine("You typed: '{0}'.", result);
If you want to read one character at a time (which sounds a bit odd to me), then you could do something like:
// Initialise the result to nothing.
string result = string.Empty;
// Prompt for input.
Console.WriteLine("Please enter your 10-digit phone number: ");
do
{
string input = Console.ReadKey().KeyChar.ToString();
// Replace any characters that are not numbers with the empty string (remove them).
result += Regex.Replace(input, "[^0-9]", string.Empty);
}
while (result.Length != 10);
// Do something with the result.
Console.WriteLine("You typed: '{0}'.", result);

Categories