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);
}
}
Related
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 ;-)
This is my class:
using System;
using System.Collections.Generic;
using System.Text;
namespace Num2Wrd
{
public class NumberToEnglish
{
public String changeNumericToWords(double numb)
{
String num = numb.ToString();
return changeToWords(num, false);
}
public String changeCurrencyToWords(String numb)
{
return changeToWords(numb, true);
}
public String changeNumericToWords(String numb)
{
return changeToWords(numb, false);
}
public String changeCurrencyToWords(double numb)
{
return changeToWords(numb.ToString(), true);
}
private String changeToWords(String numb, bool isCurrency)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
String endStr = (isCurrency) ? ("Only") : ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/Rupees
endStr = (isCurrency) ? ("Rupees " + endStr) : ("");
pointStr = translateRupees(points);
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch
{
;
}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");
int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch
{
;
}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
private String translateRupees(String Rupees)
{
String cts = "", digit = "", engOne = "";
for (int i = 0; i < Rupees.Length; i++)
{
digit = Rupees[i].ToString();
if (digit.Equals("0"))
{
engOne = "Zero";
}
else
{
engOne = ones(digit);
}
cts += " " + engOne;
}
return cts;
}
}
}
Form contains two Textboxes (textBox1 and textBox2) and a Button(button1).
I want to type an amount in numbers in textBox1 and click on the button. The amount entered in numbers in textBox1 has to be converted to text and appear in textbox2. Functions to convert are in above C# class file. I am a new student. Can anyone help me in solving this problem.
You have to create an object for 'NumberToEnglish' Class and use it in Form1.cs this way
public partial class Form1 : Form
{
NumberToEnglish neObj = new NumberToEnglish();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = neObj.changeCurrencyToWords(Convert.ToDouble(textBox1.Text));
}
}
public partial class Form1 : Form
{
NumberToEnglish Obj = new NumberToEnglish();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = Obj.changeCurrencyToWords(textBox1.Text);//As your method accept a string..
}
}
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox><br />
<br />
<asp:TextBox ID="TextBox2" runat="server" Height="100px" TextMode="MultiLine" Width="600px"></asp:TextBox>
</div>
</form>
And my code behind code is:
public String changeToWords(String numb)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
String endStr = ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = ("point");// just to separate whole numbers from points/Rupees
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch
{
;
}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");
int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch
{
;
}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox2.Text = changeToWords(TextBox1.Text);
}
it is working properly but what i want is when i am typeing in textbox it automatically shows in another textbox and I want to show numbers to words in lakhs also.... please help me
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I 've an actual function which replace specific chars by others specific chars in a string.
It works fine but I find this function is ugly. How I can replace this function by a more elegant function ?
private string CorrectString(string data)
{
string retData = string.Empty;
for (int j = 0; j < data.Length; j++)
{
char myChar = data[j];
switch (myChar)
{
case 'à':
myChar = '#';
break;
case 'ç':
myChar = '\\';
break;
case '[':
myChar = '°';
break;
case '!':
myChar = '!';
break;
case 'é':
myChar = '{';
break;
case 'è':
myChar = '}';
break;
case ']':
myChar = '§';
break;
case '¦':
myChar = 'ù';
break;
case '`':
myChar = 'µ';
break;
case '#':
myChar = '£';
break;
case '#':
myChar = 'à';
break;
case '°':
myChar = '[';
break;
case '¤':
myChar = '€';
break;
case 'µ':
myChar = '`';
break;
case '~':
myChar = '"';
break;
case 'Ý':
myChar = 'Ý';
break;
case '¢':
myChar = '¢';
break;
case '£':
myChar = '#';
break;
case '§':
myChar = ']';
break;
case '¬':
myChar = '¬';
break;
case '|':
myChar = '|';
break;
case '"':
myChar = '~';
break;
case '{':
myChar = 'é';
break;
case '}':
myChar = 'è';
break;
case 'ù':
myChar = '¦';
break;
case '\\':
myChar = 'ç';
break;
}
retData = retData.Insert(j, myChar.ToString());
}
return retData;
}
Solution 1
You can simply hold your characters in two strings:
var toTranslate = "àç[!é...";
var translateTo = #"#\°...";
and then translate as you find the characters:
int index = toTranslate.IndexOf(myChar);
if (index > -1)
{
myChar = translateTo[index];
}
Solution 2
Another, efficient but less readable way would be to store a Dictionary<char, char> and to use it like so:
myDictionary['à'] = '#';
myDictionary['ç'] = '\\';
...
if (myDictionary.Keys.Contains(myChar))
{
myChar = myDictionary[myChar];
}
If speed is not a concern, you might want to create a Dictionary<char, char> and for each key of the dictionary, check whether it is equal to a current character. If it is, then replace it by the appropriate value. Advance one character and continue.
Or a sequence of Replace statements:
myCleanString= Regex.Replace(data, "à", #"#")
.Replace("ç", "\\")
.Replace("[", "°") ...
_MyString1 = "#\\°!"; // those you put in the partial class or public class of your program
_MyString1 = "#\\°!";
string c = _MyString1.Substring(_MyString.IndexOf("à"),1);
I can written an application which converts strings (made of numbers) from 8 - 12 characters in length (see examples below)
1404336133
4174728823
0587035281
Basically I want to convert the strings above into a specific format (stored in a config file) for the time being its as shown below.
<add key="Consumer_Code_Format_For_Code_Length_Eight" value="#### ####"/>
<add key="Consumer_Code_Format_For_Code_Length_Nine" value="### ### ###"/>
<add key="Consumer_Code_Format_For_Code_Length_Ten" value="### #### ###"/>
<add key="Consumer_Code_Format_For_Code_Length_Eleven" value="#### ### ###"/>
<add key="Consumer_Code_Format_For_Code_Length_Twelve" value="#### #### ####"/>
I am currently using the following code to format the codes ...
public static string FormatCode(string code)
{
switch (code.Length.ToString())
{
case "8":
string codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eight"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
case "9":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Nine"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
case "10":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Ten"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
case "11":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eleven"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
case "12":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Twelve"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
default:
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eight"];
code = String.Format("{0:" + codeFormat + "}", Double.Parse(code));
break;
}
// Finally return the newly formatted code
return code;
}
However, for the code 0587035281 it displays "58 7035 281" therefore removing the leading zero which I require.
Any ideas how to stop this and also is there anything wrong or suspicious with my code?
Looking forward to your reply
public static string FormatCode(string code)
{
switch (code.Length.ToString())
{
case "8":
string codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eight"];
break;
case "9":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Nine"];
break;
case "10":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Ten"];
break;
case "11":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eleven"];
break;
case "12":
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Twelve"];
break;
default:
codeFormat = ConfigurationManager.AppSettings["Consumer_Code_Format_For_Code_Length_Eight"];
break;
}
char[] result = new char[codeformat.Length];
int used = 0;
for(i = 0; i < codeformat.Length; i++)
{
if (codeformat[i] == '#')
{
result[i] = code[used];
used++;
}
else
result[i] = codeformat[i];
}
// Finally return the newly formatted code
return new string(result);
}
Doublevalues are actually stored as numbers, so leading zeroes are being automatically removed when using Double.Parse().
Tho add the nleading zeroes once again, you can do something similar to this (not tested, written from the top of my head.) Remember the original length, then compare the result and add as many leading zeroes as required.
public static string FormatCode(string code)
{
int originalLength = code.Length;
switch (originalLength)
{
case 8:
string codeFormat = ...;
code = ...;
break;
case 9:
codeFormat = ...;
code = ...;
break;
// ...
while (code.Length < originalLength) {
code = "0" + code;
}
return code;
}
There's no pretty solution you can do inline, you'll have to do your own processing. Since this is not really a number you're dealing with, and maybe you may need to have some non-numeric literals there, best that you just insert a space every N characters. This would go something like this:
int chunkSize = 3;
string a = "0123456789";
int len = a.Length;
StringBuilder sb = new StringBuilder(len + len / chunkSize);
int firstIdx = len % chunkSize;
sb.Append(a.Substring(0, firstIdx));
sb.Append(" ");
for (int i = firstIdx; i < len; i += chunkSize)
{
sb.Append(a.Substring(i, chunkSize));
sb.Append(" ");
}
a = sb.ToString();