0

I'm trying to create random character combination. Then I'd like to output it on the console. The following code does work as long as I'm using string instead of char datatypes.

The problem with using just sting datatype is, that the output will only be in upper case and I can't simply lowercase everything and only uppercase the first string.

So I tried to do it with a char array appending every character to a stringBuilder. But somehow I can't Console.WriteLine what I coded. and I don't know why... Do you guys maybe have a hint for solving the issue?

cheers

    using System;

namespace WinGen
{
    public class NamenGenerator
    {
        private int NamenLaenge { get; set; }
        private char[] BuchstabenKombination { get; set; }
        private int CharShifter { get; set; }
        private int CharPicker { get; set; }
        private int RangeMin { get; set; }
        private int RangeMax { get; set; }

        public NamenGenerator()
        {
            Random _namenLaenge = new Random();
            this.NamenLaenge = _namenLaenge.Next(4, 10);
            CharShifter = 0;
            RangeMin = 0;
            RangeMax = 25;
            BuchstabenKombination = new char[this.NamenLaenge];
        }

        public void StringGenerator()
        {
            try
            {
                while (this.NamenLaenge != 0)
                {
                    Random charakter = new Random();
                    CharPicker = charakter.Next(RangeMin, RangeMax);
                    BuchstabenKombination[CharShifter] = Convert.ToChar((Buchstaben)CharPicker);
                    this.NamenLaenge--;
                    this.CharShifter++;
                }

                StringBuilder sb = new StringBuilder();
                string t = string.Empty;

                foreach (char c in BuchstabenKombination)
                {
                    t = Convert.ToString(c);
                    sb.Append(t);
                    Console.WriteLine(t);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            
        }
    }
}
Dr.Sun
  • 9
  • 7
  • Assuming you don't need the `Console.WriteLine` and you just need the overall result, why not use `string result = new string(BuchstabenKombination); Console.WriteLine(result);` instead? – ProgrammingLlama Jun 03 '22 at 07:54
  • Or do you mean you want `Console.WriteLine(sb.ToString());`? Oh and `sb.Append(c);` instead of converting to `string t` and appending that? – ProgrammingLlama Jun 03 '22 at 07:55
  • well many thanks. But I think my VS has en issue. Because Console.WriteLine() does not output anything at all. Even if I'm using Debug.WriteLine() there is no output. does someone know why? I just want do make sure that this is not the main issue of my initial question... – Dr.Sun Jun 03 '22 at 08:51
  • Well, you seem to be randomly choosing characters 0 to 25, [which are control codes, etc.](https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/ASCII-Table.svg/1261px-ASCII-Table.svg.png). Are you trying to get letters? – ProgrammingLlama Jun 03 '22 at 08:54
  • Correct - the letters are in a separate Enum class A-Z. I "pick" them randomly and assign them to the array "BuchstabenKombination". Then at the end I want (for control purpose) output the string "BuchstabenKombination". All letters should be lowercase the first one should be uppercase... But as mentioned, no output at all... I tried it your way and I getting at least the length of the string "result"... – Dr.Sun Jun 03 '22 at 09:05
  • Um, enums are basically integers with names... change your code to `Convert.ToChar(CharPicker + 65);` and see if it works. – ProgrammingLlama Jun 03 '22 at 09:10
  • now it work at least with outputting the random combinations to the console but still everything in uppercase. What does the +65 do. Never saw that before... – Dr.Sun Jun 03 '22 at 09:19
  • 65 is the ASCII code of the letter A. – ProgrammingLlama Jun 03 '22 at 09:21
  • Does my answer help you achieve what you're trying to do? – ProgrammingLlama Jun 03 '22 at 09:24

1 Answers1

0

So you can rewrite your loop like this:

foreach (char c in BuchstabenKombination)
{
    sb.Append(c);
}
Console.WriteLine(sb.ToString());

This will print the entire completed string to the console.

The other issue is that you're generating characters between 0 and 25, which are mostly control codes according to the ASCII chart. I understand that you tried to mitigate this by using an enum, but enums are essentially named integer values, so you're basically still generating characters from 0 and 25 on the ASCII chart.

To verify this, you can change your code to

BuchstabenKombination[CharShifter] = Convert.ToChar(CharPicker + 65); // aka CharPicker + 'A'

This will now generate characters A-Y.

I imagine you created an enum so that you can choose from a set of characters. Overall, I'd rewrite your code like this:

Random charakter = new Random();
StringBuilder sb = new StringBuilder();
int desiredLength = 5;
const string characters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < desiredLength; ++i)
{
    int charIdx = charakter.Next(0, characters.Length);
    sb.Append(characters[charIdx]);
}
Console.WriteLine(sb.ToString()); // outputs a 5 character long string with characters randomly chosen from the characters string

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • wow - you really try to help. many thanks... let my try I will come back on this soon... and yes, your assumptions are correct... – Dr.Sun Jun 03 '22 at 09:24
  • @Dr.Sun I also meant to say that you shouldn't generally create `Random` in loops. In .NET Framework (but not .NET Core, .NET 5+) it was typically instantiated using the system time as the random seed, so you could end up creating many `Random` objects in a fast loop that would with return the same value each time. You can read more about that [here](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number). – ProgrammingLlama Jun 03 '22 at 09:27
  • 1
    thank you @DiplomacyNotWar you helped a lot. I think I get rid of the Enum (was mistakenly chosen as a "DB" of chars". I will work with an array including values A-Z. And regarding the Random() in loop: didn't know that yet expected it. Maybe I will work with a little timeout. so again thumbs up and thanks for your time... – Dr.Sun Jun 03 '22 at 09:44
  • @Dr.Sun Sure: https://chat.stackoverflow.com/rooms/7/c – ProgrammingLlama Jun 03 '22 at 09:50
  • Unfortunately there isn't really any other easy way. Sorry. It's probably not super important to me though (I'm British living in Japan, far from any war, etc.). I just would rather see involved parties (ideally in any conflict) sit down with each other and work out their differences rather than sending young soliders to their likely deaths, hence my username. – ProgrammingLlama Jun 03 '22 at 09:55
  • Considering my home country rejected changing to the "alternative vote" system from the "first past the post" voting system, I'm not sure the issue is so much developing such a system as getting countries to accept it and use it. As for your specific project, I'm afraid I'm not interested in being part of it. Good luck though! :) – ProgrammingLlama Jun 03 '22 at 10:06
  • many thanks anyway... take care...and thanks for helping me today... – Dr.Sun Jun 03 '22 at 12:05