Alex Johnson Alex Johnson - 2 years ago 123
C# Question

Adding strings to a list in C# one at a time

I'm fairly new at C# as a language so this is a fairly basic/simple problem that I've encountered. I don't quite know how to add each one of these letters into a list to present them all in a line at the end. For example, there's an 'IF/ELSE' statement but both produce a letter at the end. Here is my code so far, I would appreciate any help/input (please note, I started learning the language 2 days ago!)

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);
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;
string newText = character.ToString();
}
else
{
char character = (char)shiftUnicode;
string newText = character.ToString();
}

}
Console.ReadLine();
}
}
}

Answer Source

You need to keep in memory each character you have 'encrypted' and just when you exit from the loop you can build the new 'encrypted' string

....
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);
....
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download