Reputation: 604
I'm trying to convert a string of characters into each characters decimal form and seperating them with a symbol that is chosen at random and then after that's converted, seperating the decimal numbers from the string and then adding 1 to those numbers and then converting them back into ASCII characters. Here's what I have so far but it keeps saying invalid input format with 'int.Parse':
public string Encode(string data, out string asciiString) {
char[] dataArray = data.ToCharArray();
string[] symb = {"@","#","$","%","&"};
Random rnd = new Random();
string newData = "";
for(int i = 0; i < dataArray.Length; i++) {
newData += (((int)dataArray[i] + 1) + symb[rnd.Next(0, 5)].ToString()); // add 1 to the decimal and then add symbol
}
asciiString = ConvertToAscii(newData);
return newData;
}
public string ConvertToAscii(string data) {
string[] tokens = data.Split('@', '#', '$', '%', '&');
data = data.TrimEnd('@', '#', '$', '%', '&');
string returnString = "";
for(int i = 0; i < tokens.Length; i++){
int num = int.Parse(tokens[i]);
returnString += (char)num;
}
return returnString;
}
Here's an example:
Normal: "Hello" converted to decimal with symbols: 72$101&108#108@111% converted to ascii (without symbols and adding 1): Ifmmp (I had to do it with an ascii table)
Upvotes: 0
Views: 383
Reputation: 116108
Have you tried to use
string[] tokens = data.Split(new char[]{'@', '#', '$', '%', '&'},StringSplitOptions.RemoveEmptyEntries);
Upvotes: 0
Reputation: 96477
The data.Split
call contains an empty string (check the tokens
result). You can remove empty entries as follows:
string[] tokens = data.Split(new[] {'@', '#', '$', '%', '&'},
StringSplitOptions.RemoveEmptyEntries);
Upvotes: 1
Reputation: 78262
You should switch these lines around so you can avoid calling Parse with an empty string.
string[] tokens = data.Split('@', '#', '$', '%', '&');
data = data.TrimEnd('@', '#', '$', '%', '&');
Upvotes: 3
Reputation: 2731
int.TryParse is almost always the better way to handle parsing to int. It takes two arguments, try replacing:
int num = int.Parse(tokens[i]);
with
int num;
if (!int.TryParse(tokens[i], out num))
{
Debug.WriteLine(string.Format("'{0}' can't be converted to an int.", tokens[i]));
}
and you will see what is going on with the failed parse.
Upvotes: 3