编码器转换为解码字符串

时间:2016-11-07 21:33:50

标签: c# arrays string decode encode

使用手工制作的代码,假设将用户的输入编码为不同的东西(他们输入的字母后面的字母)。每当我尝试运行它时,返回只是用户的句子。我很高兴它适用于解码器,但编码器需要对消息进行编码。我想知道它为什么不起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EncoderDecoder
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Please enter a sentence. No numbers, smybols, or punctuations.");
            string sentence = Console.ReadLine();
            Console.WriteLine();


            Console.WriteLine("Your encoded message.");
            string encodedSentence = Encode(sentence);
            Console.WriteLine(encodedSentence);

            Console.WriteLine("Your decoded message. Also known as your original message.");
            string decodedSentence = Decode(sentence);
            Console.WriteLine(decodedSentence);

            Console.ReadLine();
        }

        private static string Decode(string encodedSentence)
        {
            char[] wordArray;
            string[] words = encodedSentence.Split(' ');
            for (int i = 0; i > words.Length; i++)
            {
                wordArray = words[i].ToArray();
                if (wordArray.Length > 1)
                {
                    char beginLetter = wordArray[0];
                    wordArray[0] = wordArray[wordArray.Length + 1];
                    wordArray[wordArray.Length + 1] = beginLetter;
                }
                for (int t = 0; t < wordArray.Length; t++)
                {
                    wordArray[t] = (char)(wordArray[t] + 1);
                }
                words[i] = new string(wordArray);
            }
            string decoded = string.Join(" ", words);
            return decoded;
        }

        private static string Encode(string sentence)
        {
            char[] wordArray;
            string[] words = sentence.Split(' ');
            for (int i = 0; i > words.Length; i++)
            {
                wordArray = words[i].ToArray();
                if (wordArray.Length > 1)
                {
                    char beginLetter = wordArray[0];
                    wordArray[0] = wordArray[wordArray.Length - 1];
                    wordArray[wordArray.Length - 1] = beginLetter;
                }
                for(int t = 0; t > wordArray.Length; t++)
                {
                    wordArray[t] = (char)(wordArray[t] + 1);
                }
                words[i] = new string(wordArray);
            }
            string encoded = string.Join(" ", words);
            return encoded;
        }

    }
 }

使用数组,我将字符串拆分为数组,然后使用该数组分别更改字母。由于某种原因,它不起作用......

2 个答案:

答案 0 :(得分:1)

两者都错了,请尝试:for (int i = 0; i < words.Length; i++)

答案 1 :(得分:0)

在for循环中的编码器中,你有t&gt; word array.length应该小于