none
How to join strings from an array into a single string and display it RRS feed

  • Question

  • So I am completely new to C#. I have experience in Python and am now trying to learn C#. So after watching some youtube videos to lean a little about the language I thought I would try to replicate a simple program I wrote in Python. All it does is choose random characters ant combines them into a string to create random passwords. The problem that I am having is I can't get the characters to join into one string so I can display it in the console window. When I try to have the console write the password nothing displays. 

    This is my code:

    MyLib:

    namespace MyLib
    {
        public class Rand
        {
            private static Random Generator = new Random();
            public static Char RandChar(string items) //Choose a 
    random char from string
            {
                int myIndex = Generator.Next(items.Length);
                char l = items[myIndex];
                return l;
            } //I remove the rest of code here because it is not needed
         }
    }
    Password genererator:
    using MyLib;
    
    namespace learning
    {
        public static class Password
        {
            private static string Letters = "abcdefghijklmnopqrstuvwxyz";
            private static string Numbers = "1234567890";
            private static string Symbols = "!@#$%^&*()";
    
            public static string Generate()
            {
                string word = "";
                string[] letters = new string[10];
                string[] choice = { "letter", "number", "symbol" };
                string[] UL = { "uper", "lower" };
                string get;
                char c;
                for (int i = 0; i <= 9; i++)
                {
                    get = Rand.RandString(choice);
                    if (get == "letter")
                    {
                        c = Rand.RandChar(Letters);
                        get = Rand.RandString(UL);
                        if (get == "uper")
                        {
                            c = char.ToUpper(c);
                            letters.Append(c.ToString());
     
                        }
                        else
                        {
                            letters.Append(c.ToString());
     
                        }
                    }
                    if (get == "number")
                    {
                        c = Rand.RandChar(Numbers);
                        letters.Append(c.ToString());
    
                    }
                    if (get == "symbol")
                    {
                        c = Rand.RandChar(Symbols);
                        letters.Append(c.ToString());
    
                    }
                }
                return String.Join(",",letters);
            }
        }
    }
    namespace learning
    {
        class Program
        {
            static void Main(string[] args)
            {
                string _word = Password.Generate();
                Console.WriteLine(_word);
            } 
         }
    }
    All I get is a bunch of commas or blank spaces.



    Sunday, September 22, 2019 12:38 AM

Answers

  • Hi LavaCreeperKing,

    Thank you for posting here.

    According to your description, you want to join strings from an array into a single string and display it.
    If you insist on using arrays, you could replace that line:

    letters.Append(c.ToString());
    with: letters[i] = c.toString();  

    And if you just want to show your random password, you can use StringBuilder to do that.

    The following code is the second way:

    public static class Password
        {
            private static string Letters = "abcdefghijklmnopqrstuvwxyz";
            private static string Numbers = "1234567890";
            private static string Symbols = "!@#$%^&*()";
    
            public static string Generate()
            {
                //string[] letters = new string[10];
                StringBuilder letters = new StringBuilder();
    
                string[] choice = { "letter", "number", "symbol" };
                string[] UL = { "uper", "lower" };
                string get;
                char c;
                for (int i = 0; i <= 9; i++)
                {
                    get = Rand.RandString(choice);
                    if (get == "letter")
                    {
                        c = Rand.RandChar(Letters);
                        get = Rand.RandString(UL);
                        if (get == "uper")
                        {
                            c = char.ToUpper(c);
                            letters.Append(c.ToString());
                       }
                        else
                        {
                            c = char.ToLower(c);
                            letters.Append(c.ToString());
                        }
                    }
                    if (get == "number")
                    {
                        c = Rand.RandChar(Numbers);
                        letters.Append(c.ToString());
                    }
                    if (get == "symbol")
                    {
                        c = Rand.RandChar(Symbols);
                        letters.Append(c.ToString());
                    }
                }
              /*  
               *   I'm sorry but i don't know why you use
               *   String.Join(",", letters); to insert ',' into your string 
               *   if you really need that ,you can use the loop to add
               */
    
                //for (int i = letters.Length-1; i >0; i--)
                //{
                //    letters.Insert(i,",");
                //}
                return letters.ToString();
            }
        }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.




    Monday, September 23, 2019 3:20 AM
    Moderator

All replies

  • Replace all of ‘letters.Append( c.ToString( ) )’ with:

       letters[i] = c.ToString( );

     

    Check if it works. If you do not need commas, then remove the return line and replace it with:

       return string.Concat( letters );

    Sunday, September 22, 2019 5:16 AM
  • Hello LavaCreeperKing,

    1. The RandString() method is missing from your code listing in the OP. I have thus attempted to create one based on the principles observed in RandChar() :

            public static String RandString(string[] strArray)
            {
                int myIndex = Generator.Next(strArray.Length);
                String l = strArray[myIndex];
                return l;
            }

    2. OK, on to the problem in the Password.Generate() method.

    2.1 The issue is that letters.Append() will return a new IEnumerable<string> object with the new string appended at the end. The original letters string array will not be modified.

    2.2 To achieve the effect that I believe you want (which is to append strings to the letters array), do the following :

    - Declare the letters array as an array of initial size 0, i.e. :

    string[] letters = new string[0];

    - As you call letters.Append(), add a call to ToArray() and then assign the result back to letters, i.e. :

    letters = letters.Append(c.ToString()).ToArray();

    3. The following is a modified version of Generate() for illustration :

            public static string Generate2()
            {
                string word = "";
                //string[] letters = new string[10];
                // Change to :
                string[] letters = new string[0];
                string[] choice = { "letter", "number", "symbol" };
                string[] UL = { "uper", "lower" };
                string get;
                char c;
                for (int i = 0; i <= 9; i++)
                {
                    get = Rand.RandString(choice);
                    if (get == "letter")
                    {
                        c = Rand.RandChar(Letters);
                        get = Rand.RandString(UL);
                        if (get == "uper")
                        {
                            c = char.ToUpper(c);
                            //letters.Append(c.ToString());
                            // Change to :
                            letters = letters.Append(c.ToString()).ToArray();
    
                        }
                        else
                        {
                            //letters.Append(c.ToString());
                            // Change to :
                            letters = letters.Append(c.ToString()).ToArray();
                        }
                    }
                    if (get == "number")
                    {
                        c = Rand.RandChar(Numbers);
                        //letters.Append(c.ToString());
                        // Change to :
                        letters = letters.Append(c.ToString()).ToArray();
    
                    }
                    if (get == "symbol")
                    {
                        c = Rand.RandChar(Symbols);
                        //letters.Append(c.ToString());
                        // Change to :
                        letters = letters.Append(c.ToString()).ToArray();
    
                    }
                }
                return String.Join(",", letters);
            }
    

    3.1 My code change recommendations are given with the comments "Change to :".

    4. Hope this will be helpful.

    - Bio.


    Please visit my blog : http://limbioliong.wordpress.com/

    Sunday, September 22, 2019 5:30 AM
  • So I am completely new to C#. I have experience in Python and am now trying to learn C#. So after watching some youtube videos to lean a little about the language I thought I would try to replicate a simple program I wrote in Python. All it does is choose random characters ant combines them into a string to create random passwords. The problem that I am having is I can't get the characters to join into one string so I can display it in the console window. When I try to have the console write the password nothing displays. 


    Numerous issues with the code you posted. Firstly, you should always post code
    snippets or examples that others can actually compile. They can then test it, 
    alter it, and illustrate solutions with the actual code. When you post heavily
    redacted code excerpts it makes it much more difficult to reconstruct the code
    and the problems, with actual solutions.

    In the code you posted you are invoking the class member method RandString
    but have not posted the code for that method.

    If your desired end result is a string then I don't know why you are converting
    characters to strings and storing them in an array of strings. Why not just
    build the final string by concatenating the characters? Why convert characters 
    to strings and then convert those strings back into characters to append to a
    string?

    If you insist on creating an array of strings from the individual letters, and
    then want to convert those strings back into letters which you concatenate into
    a string:

    using System;
    
    namespace learning
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] strarr = new string[] {"A","B","C" };
                string str = "";
                str = string.Concat(strarr);
    
                Console.WriteLine(str);
            }
        }
    }
    

    - Wayne

    Sunday, September 22, 2019 5:48 AM
  • Hi LavaCreeperKing,

    Thank you for posting here.

    According to your description, you want to join strings from an array into a single string and display it.
    If you insist on using arrays, you could replace that line:

    letters.Append(c.ToString());
    with: letters[i] = c.toString();  

    And if you just want to show your random password, you can use StringBuilder to do that.

    The following code is the second way:

    public static class Password
        {
            private static string Letters = "abcdefghijklmnopqrstuvwxyz";
            private static string Numbers = "1234567890";
            private static string Symbols = "!@#$%^&*()";
    
            public static string Generate()
            {
                //string[] letters = new string[10];
                StringBuilder letters = new StringBuilder();
    
                string[] choice = { "letter", "number", "symbol" };
                string[] UL = { "uper", "lower" };
                string get;
                char c;
                for (int i = 0; i <= 9; i++)
                {
                    get = Rand.RandString(choice);
                    if (get == "letter")
                    {
                        c = Rand.RandChar(Letters);
                        get = Rand.RandString(UL);
                        if (get == "uper")
                        {
                            c = char.ToUpper(c);
                            letters.Append(c.ToString());
                       }
                        else
                        {
                            c = char.ToLower(c);
                            letters.Append(c.ToString());
                        }
                    }
                    if (get == "number")
                    {
                        c = Rand.RandChar(Numbers);
                        letters.Append(c.ToString());
                    }
                    if (get == "symbol")
                    {
                        c = Rand.RandChar(Symbols);
                        letters.Append(c.ToString());
                    }
                }
              /*  
               *   I'm sorry but i don't know why you use
               *   String.Join(",", letters); to insert ',' into your string 
               *   if you really need that ,you can use the loop to add
               */
    
                //for (int i = letters.Length-1; i >0; i--)
                //{
                //    letters.Insert(i,",");
                //}
                return letters.ToString();
            }
        }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.




    Monday, September 23, 2019 3:20 AM
    Moderator
  • Hi, thank you. As I said I am new to C# and I was trying to figure out how to re-create a program I wrote in Python. Yes I know I accidentally removed some of the needed code, I'm sorry. Also as for the string.join() part, I was trying that because it worked in Python so I thought it world work in C#. I tried to post my Python code to show you what I was trying to do, but for some reason it did not work. Thanks for the help the string builder worked. 
    Monday, September 23, 2019 3:09 PM