简体   繁体   中英

C# - int.Parse help?

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)

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.

You should switch these lines around so you can avoid calling Parse with an empty string.

string[] tokens = data.Split('@', '#', '$', '%', '&');
data = data.TrimEnd('@', '#', '$', '%', '&');

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);

您是否尝试过使用

string[] tokens = data.Split(new char[]{'@', '#', '$', '%', '&'},StringSplitOptions.RemoveEmptyEntries);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM