一次将字符串添加到C#中的列表中

时间:2017-10-02 18:35:37

标签: c# list

我是C#作为一种语言的新手,所以这是我遇到的一个相当基本/简单的问题。我不太清楚如何将这些字母中的每一个添加到列表中,以便最后将它们全部显示在一行中。例如,有一个'IF / ELSE'语句,但两者都在最后生成一个字母。这是我的代码到目前为止,我将不胜感激任何帮助/输入(请注意,我2天前开始学习该语言!)

data check;
length sqn 8. cat $100.;
input  sqn   cat $;
datalines;
1   Uncoded
2   Uncoded
3   ABNORMAL-MENSTRUATION-DIAGNOSTIC-CURETTAGE-OF-THE-UTERINE-CAVITY.
3   ANXIETY
3   CARPAL-TUNNEL-SYNDROME
3   EXACERBATION
 ;
run;

2 个答案:

答案 0 :(得分:1)

您需要将每个已加密的字符保留在内存中,并且当您退出循环时,您可以构建新的“加密”字符串

....
List<char> newChars = new List<char>();
foreach (char c in lower)
{
    int unicode = c;
    int shiftUnicode = unicode + shift;
    //Console.WriteLine(shiftUnicode);
    if (shiftUnicode >= 123)
    {
        int overflowUnicode = 97 + (shiftUnicode - 123);
        char character = (char)overflowUnicode;
        newChars.Add(character);    
    }
    else
    {
        char character = (char)shiftUnicode;
        newChars.Add(character);
    }
}

string newString = new string(newChars.ToArray());
Console.WriteLine(newString);
....

答案 1 :(得分:0)

我认为您要做的是将每个字符添加到字符串中。您尝试使用名为newText的变量执行此操作,但随着循环继续,newText的值将被覆盖。

if (shiftUnicode >= 123)
{
    int overflowUnicode = 97 + (shiftUnicode - 123);
    char character = (char)overflowUnicode;

    // value gets overwritten here
    string newText = character.ToString();
}
else
{
    char character = (char)shiftUnicode;

    // value gets overwritten here
    string newText = character.ToString();
}

您需要做的是:
- 在newText循环上方定义foreach,以便您可以访问其范围 - 将任何新的字符添加到newText的末尾,而不是覆盖其值 - 使用newText

Console.WriteLine()的值打印到控制台
using System;
namespace caesarCipher
{
    class Program
    {
        static void Main(string[] args)
        {
            string text;
            Console.WriteLine("Enter the text to encrypt ");
            text = System.Convert.ToString(Console.ReadLine());
            string lower = text.ToLower();
            Random rnd = new Random();
            int shift = rnd.Next(1, 25);

            // declare and initialize newText here
            string newText = string.Empty;
            foreach (char c in lower)
            {
                int unicode = c;
                int shiftUnicode = unicode + shift;
                Console.WriteLine(shiftUnicode);
                if (shiftUnicode >= 123)
                {
                    int overflowUnicode = 97 + (shiftUnicode - 123);
                    char character = (char)overflowUnicode;

                    // append the new character to newText
                    newText += character;
                }
                else
                {
                    char character = (char)shiftUnicode;

                    // append the new character to newText
                    newText += character;
                }

            }

            // Print the value of newText to the Console
            Console.WriteLine(newText);
            Console.ReadLine();
        }
    }
}