Resolved Help - How to check if a string is filled?

ICauseDarkDays

New member
Joined
Apr 17, 2022
Messages
3
Programming Experience
Beginner
I am creating a Text-Based game, and when I first started, I just made it so that if you skipped past the naming process, you would be given a name, but I don't want players to skip past the process anymore. I want them to pick their names out intentionally, but I don't know how to make it so that this line of code would pick up on if you put any random name in there and let you pass.

I also like doing easter eggs with the names, hence all the "if" statements for certain names, and I thought I could use an "else if" to detect any name that a player would put in there but I have no idea how to do that. any help?

If you need more information, let me know, thanks.


Naming Process:
while (hasName == false)
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine();
                Console.WriteLine("              ████████╗ █████╗ ██╗     ███████╗     ██████╗ ███████╗    ██╗  ██╗███████╗██████╗  ██████╗");
                Console.WriteLine("              ╚══██╔══╝██╔══██╗██║     ██╔════╝    ██╔═══██╗██╔════╝    ╚██╗██╔╝██╔════╝██╔══██╗██╔════╝");
                Console.WriteLine("                 ██║   ███████║██║     █████╗      ██║   ██║█████╗       ╚███╔╝ █████╗  ██████╔╝██║     ");
                Console.WriteLine("                 ██║   ██╔══██║██║     ██╔══╝      ██║   ██║██╔══╝       ██╔██╗ ██╔══╝  ██╔══██╗██║     ");
                Console.WriteLine("                 ██║   ██║  ██║███████╗███████╗    ╚██████╔╝██║         ██╔╝ ██╗███████╗██║  ██║╚██████╗");
                Console.WriteLine("                 ╚═╝   ╚═╝  ╚═╝╚══════╝╚══════╝     ╚═════╝ ╚═╝         ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝ ╚═════╝");
                Console.WriteLine();
                Console.WriteLine("I'm sorry, traveller, I seem to have forgotten your name. May you remind me?\n");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("Your Name: ");
                string name = Console.ReadLine();
                Console.ForegroundColor = ConsoleColor.White;

                if (name == "Link")
                {
                    atk = 999;
                    gold = 999;
                    def = 999;
                    hp = 999;
                    maxhp = 999;
                    mana = 999;
                    divine = true;
                    fire = false;
                    head = "Elf hat";
                    chest = "Elf Tunic";
                    legs = "Elf Linen";
                    boots = "Elf Boots";
                    hasName = true;
                    Console.WriteLine("\nJust as the prophecy has foretold...");
                    Console.ReadLine();
                }
                if (name == "Boyce")
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("\nYou have obtained: The Sword of Dr. Pepper");
                    weaponname = "The Sword of Dr. Pepper";
                    hasName = true;
                    Console.ReadLine();
                }
                if (name == "Derek")
                {
                    Console.WriteLine("\nGood luck on your Journey, cheater.");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("\nDifficulty has been set to: INSANE");
                    hasName = true;
                    Console.ReadLine();
                }
                if (name == "Tyler")
                {
                    Console.WriteLine("\nYou thought flattery would get you somewhere... hahaha!");
                    Console.ReadLine();
                    Console.WriteLine("Well you were right...");
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("\nGODMODE SET");
                    hp = 1000000;
                    maxhp = 1000000;
                    hasName = true;
                    Console.ReadLine();
                }
                if (name == "Captain")
                {
                    Console.WriteLine("\nYou'll meet Tennille later.");
                    hasName = true;
                    Console.ReadLine();
                }
                if (name == "")
                {
                    name = "Speedrunner";
                    hasName = true;
                    Console.WriteLine("\nYou left your name area blank, so we picked one out for you.");
                }
                if (name == "Speedrunner")
                {
                    Console.WriteLine("\nGood luck.");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("\nDifficulty has been set to: INSANE");
                    hp = 1;
                    maxhp = 1;
                    atk = 5;
                    def = 0;
                    hasName = true;
                    Console.ReadLine();
                }
                else if ()
                {
                    hasName = true;
                }
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\n" + name + "... ah, yes, that's right... " + name + "...");
            Console.WriteLine("\nNow onto the story!");
            Console.ReadLine();
 
Solution
Finally got it! I used Skydiver's advice and put String.IsNullOrWhiteSpace() before line 19 in an if statement, and in order to check if the string even had a value to let them pass the naming stage, I found out about value.Trim().Length >= 1 which basically tells the system that if the string has 1 or more characters, no matter what they are, you're free to pass. Thanks!

Perfection:
                if (String.IsNullOrWhiteSpace(name))
                {
                    Console.WriteLine("\nThe Prophecy forbids this name, I am afraid.");
                    Console.ReadLine();
                }
                if (name.Trim().Length >= 1)
                {
                    hasName = true...
how to make it so that this line of code would pick up on if you put any random name in there and let you pass.
Yeah, that is a difficult problem to determine if they put in a random name vs. an intentional name.

The only thing you can do is to either only prevent them from moving forward if they put in a name that is an empty string or all whitespace. Depending on your naming rules, you might also specify that character names may contain punctuation, but may not be all punctuation. You may also have rules about whether emojis are allowed in names or not.

As for your Easter egg names, you should be doing those checks after you have accepted a name that satisfies your naming rules. I recommend using either a switch statement, or create a dictionary of names and actions to perform.


 
Last edited:
Yeah, that is a difficult problem to determine if they put in a random name vs. an intentional name.

The only thing you can do is to either only prevent them from moving forward if they put in a name that is an empty string or all whitespace. Depending on your naming rules, you might also specify that character names may contain punctuation, but may not be all punctuation. You may also have rules about whether emojis are allowed in names or not.

As for your Easter egg names, you should be doing those checks after you have accepted a name that satisfies your naming rules. I recommend using either a switch statement, or create a dictionary of names and actions to perform.


Highly appreciated. Last question, how would you go about checking only if the name was null or white space in my example of code?
 
Before line 19, I would use String.IsNullOrWhitespace(). If the return value is true, I would continue back to the top of the loop.
 
Finally got it! I used Skydiver's advice and put String.IsNullOrWhiteSpace() before line 19 in an if statement, and in order to check if the string even had a value to let them pass the naming stage, I found out about value.Trim().Length >= 1 which basically tells the system that if the string has 1 or more characters, no matter what they are, you're free to pass. Thanks!

Perfection:
                if (String.IsNullOrWhiteSpace(name))
                {
                    Console.WriteLine("\nThe Prophecy forbids this name, I am afraid.");
                    Console.ReadLine();
                }
                if (name.Trim().Length >= 1)
                {
                    hasName = true;
                    Console.WriteLine("\nYou may pass.");
                    Console.ReadLine();
                }
 
Solution
I don't think that you're really doing it properly. Do you really want to let a person save a name with leading or trailing whitespace? How would that be a valid part of a name? I think that what you should do is trim the input and then check whether it contains any characters and, if it does, save the trimmed input. There's no point checking for null because ReadLine can't return null.
C#:
name = name.Trim();

if (name == string.Empty)
{
    // fail
}
else
{
    // pass
}
You could also test if (name.Length == 0).
 
There's no point checking for null because ReadLine can't return null.
Except for the rare case that you are using an online compiler. Recall a thread where we were surprised when a poster was reporting that they were getting an null reference exception after doing a Console.ReadLine() and it was only a few posts later that we discovered that the poster was using an online compiler.
 
Except for the rare case that you are using an online compiler. Recall a thread where we were surprised when a poster was reporting that they were getting an null reference exception after doing a Console.ReadLine() and it was only a few posts later that we discovered that the poster was using an online compiler.
Looking at the most recent documentation for Console.ReadLine, the return type is declared as string?, so I guess one should probably be thorough and take the extra nanosecond required to perform the null check. Given that the Trim call would take care of values that were nothing but whitespace, IsNullOrEmpty would be the most appropriate option:
C#:
var name = Console.ReadLine()?.Trim();

if (string.IsNullOrEmpty(name))
{
 
if the string has 1 or more characters, no matter what they are, you're free to pass
Try a user that types in an single comma as their player name. Or better yet, a person who types in dollar sign as their username. The older text based games would have a fit over this because they used to use the dollar sign as an internal marker for where some string replacements would happen for their UI strings.
 
Back
Top Bottom