FAQ: Working with Text - Get Info About Strings

This community-built FAQ covers the “Get Info About Strings” exercise from the lesson “Working with Text”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn C#

FAQs on the exercise Get Info About Strings

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

1 Like

Okay, I don’t get, why the passwordCheck isn’t a bool variable. I mean, yes, you can identify if it contains a “!” easily by looking at the given int, but wouldn’t it make more sense to just check if (or if not) the password contains a “!”?

2 Likes

We can also find the position of a specific character or substring using .IndexOf() . This method is useful for searching to see if something exists in a string.

That’s only partly true, as there is actually an existing method called .Contains() that can accept parameters, and returns a boolean (either true or false).

1 Like

This task asks you to check if there are any special characters… but doesn’t tell you how. Yes, it uses an exclamation mark as an example and shows you how you could look for that specific character, but the task itself asks you to check for any special charaters, which is impossible to do with the information provided. Even the cheatsheet doesn’t show you how and there’s no linked documentation that could help either.

You have to just imply it means to only search for the exclamation mark and then ignore (as previously mentioned) that passwordCheck should obviously be a bool, but because it’s not practical with the given information you have to throw sense to the wind and use an int instead.

This is a really badly composed task, I hope at some point it’s reviewed and made more sensible.

TLDR; it’s a nonesense task, if you’re stuck just ignore the question and search for the exclamation mark only, then store the number value for the variable passwordCheck, don’t bother trying to apply logic.

3 Likes

What your asking is something typically done with Regex.

I’m sure you’re right. I haven’t used Regex myself as I’m pretty much a beginner, I’ve only used C# before in Unity and haven’t come across Regex yet, which is precisely why I’m doing this course to better understand C# given that I both use it and know very little about it.

The problem I have with this task is that you’re expected to use the information given to you up to this point to solve the problem, but up to this point there’s no mention of Regex or any other useful methods to complete the given task. You’re essentially expected to give up.

But thanks for pointing that out, I’ll look into it, I was wondering how to do the task properly and you’ve likely answered that for me, cheers

This likely wont help, but this was my solution to this task.


namespace PasswordCheck
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create password
      string password = "a92301j2add";
      // Get password length
	  int passwordLength = password.Length;
      // Check if password uses symbol
	  int passwordCheck = password.IndexOf("!");
      // Print results
      Console.WriteLine($"The user password is {password}. Its length is {passwordLength} and it receives a {passwordCheck} check.");
    }
  }
}

C# has something called .Contains()
https://docs.microsoft.com/en-us/dotnet/api/system.string.contains?view=netframework-4.8
Another option that isn’t Regex is to make an array/list/set, put all the characters you wish to check in that array/list/set, and then iterate that in a loop where you need to check which in this case would be the string.

1 Like

Yeah, I did that too, just felt to me like the answer didn’t really address the problem. Hopefully the folks at codecademy catch wind of this and change the task; even just changing the question to specifically ask for the exclamation mark would be an improvement.

Thanks for trying to help out though, we’ll just have to see if something gets changed, but this might just get burried.

3 Likes

Hi, I have just been having problems with the .IndexOf(); method, I came upon a problem. For instance, say I have the string “twitterUserPassword = “BigBlackNemesis””, and I use the Index.Of(); method to find the position of B(twitterUserPassword.IndexOf(B);), When I run this program, it returns an error. Soon after discovering this, I noticed that “B” appeared twice in “BigBlackNemesis”. Am I writing the code wrong or does the .IndexOf(); method return an error if the character you are looking for appears multiple times in a string?

Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

String.IndexOf Method

You asked it to look for B as opposed to “B”, which is a character in the string. As you are aware, computers do what we code them to do and not what we want them to do…unless we code what we mean.

It will help to review the instructions under the IndexOf heading.

where does it return the length of the string when ‘foo.length;’ is typed? if I want to return it to a variable can I write ‘int lengthOfString = foo.length;’

You’re almost there. Notice the Capitalization of methods:

int lengthOfString = foo.Length;’

Then write a C# version of an output statement.

Just to point out a lapsus most probably. String.Lenght is a property not a method and in the exercise it’s being used synonymously.
“…we can find out how many characters exist in a string with the .Length method.” but then in a paragraph below:
“We append the .Length property to a string that we have, such as a user’s tweet.”
Like I said, it’s probably a typo or something, but it could confuse ppl so it should be corrected.
Cheers and happy coding :slight_smile:

1 Like

It’s quite confusing that when you run the code for task 1 you get an error message while at the same time task 1 does show as correctly completed. I wondered if something was wrong with the exercise but it turns out it’s because the string we’re printing at the end uses a variable we haven’t created yet. It seems counterintuitive to give learners error messages when they’ve completed the exercise correctly.

1 Like

why are we using an int?

Because it returns an integer value. You cannot save it as a string variable.

I also tried to do a bool based on the information given, which obviously failed. I’m getting the sense that these lessons want us to mess up and learn from our mistakes, rather than just giving us the information directly.

I need help on this task. it keeps giving me this error: Program.cs(13,6): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement [/home/ccuser/workspace/csharp-working-with-text-get-info-about-strings/e7-workspace.csproj]

The build failed. Fix the build errors and run again.

I can’t find where the error actually is though? Here’s the code:
using System;

namespace PasswordCheck
{
class Program
{
static void Main(string args)
{
// Create password
string password = “a92301j2add”;

  // Get password length
 password.Length;

int passwordLength = password.Length;

  // Check if password uses symbol
  password.IndexOf("!");

int passwordCheck = password.IndexOf("!");

  // Print results
  Console.WriteLine($"The user password is {password}. Its length is {passwordLength} and it receives a {passwordCheck} check.");

}

}
}

To those struggling with this task…I hear you. My initial thought was that this was a bogus task, requiring us to dumb down the task to search for a single symbol, and disregard the larger task (search for ANY symbol). My initial thought was to use REGEX, but, implementing it seemed more complicated than I was prepared for. I feel that is certainly the most elegant solution. However, it is still possible without it.

Below is my solution. Ironically, the lesson won’t give me credit for it, and the only way to progress is to, in fact, dumb it down…=/. Of note, My first attempt was actually using the Contains method. I used “Contains” for no particular reason other than it seems most straight forward, but the code would function virtually identically with Index.Of. But, in the spirit of using only what tools we have, I have included the “Index.Of” version. If your interested in Cotains, it would function the same, but:

if (validCharacters.IndexOf(testString[i]) == -1)

would be

if (!validCharacters.Contains(testString[i]))

In all fairness, what is included that has not been taught yet would be the loops. in particular the for loop which iterates through the string, testing each character. This is not needed to accomplish the task per se, but was done to give a print-out of the exact symbols, at the exact location. Cheers!

using System;

namespace PasswordCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create password
            string password = "!a9(2H`~30$1j%2a?dd";

            // Get password length
            int passwordLength = password.Length;


            // Check if password uses symbol
            string validCharacters = "abcdefghijklmnopqrstuvwxyz1234567890";
            string testString = password.ToLower();
            string detectedSymbols = "";
            int symbolsCount = 0;

            for (int i = 0; i < testString.Length; i++)
            {
                if (validCharacters.IndexOf(testString[i]) == -1)
                {
                    symbolsCount++;
                    detectedSymbols += $"{testString[i]} contained at location {i + 1}\n";
                }
            }

            if (symbolsCount > 0)
            {
                Console.WriteLine($"I'm sorry, your password contains {symbolsCount} symbols.\nSpecifically:\n {detectedSymbols}");
            }
            else
            {
                Console.WriteLine("Congradulations on selecting a proper password!");
            }
        }
    }
}


when run on the string “!a9(2H`~30$1j%2a?dd” gives output:

I’m sorry, your password contains 7 symbols.
Specifically:
! contained at location 1
( contained at location 4
` contained at location 7
~ contained at location 8
$ contained at location 11
% contained at location 14
? contained at location 17

I hope this helps!

1 Like