Mossy Joules Mossy Joules - 1 month ago 6
C# Question

Use Substring method to count specific character from a string

So I am new to programming and one of my exercises involves using a substring within a loop to count the number of iterations of a specific character with a user's input.

As far as I can tell for the exercise, and what I know in C sharp so far, using a substring in this will only help read the position of a character within the input, and will not count it. I can not make heads or tails of this, and am at a loss.

I want to know how to understand this, and what ways I am missing the point of the exercise.
I need an idea of how to set the substring to read the number of a certain character type from the end-user's input from console.

This is the original question:

There is a method called Substring that we can use with a string to look at a portion of a string.

For example, the following code will print the letter a.

string input = "abcdef";
Console.WriteLine(input.Substring(0, 1));


Assignment:

Given the following input, create a loop that uses the Substring method to count the number of times the letter ā€˜zā€™ occurs in a string input by the user.

asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza


Edit: So Far I have the code to count the number of times that Z is used, but I don't know how to incorporate a substring into it

int total = 0;
var letter = new HashSet<char> { 'z' };
Console.WriteLine("Please enter your letters:");

// asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
string sentence = Console.ReadLine().ToLower();

for (int i = 0; i < sentence.Length; i++)
{
if (letter.Contains(sentence[i]))
{
total++;
}
}
Console.WriteLine("Total number of Z uses is: {0}", total);
// Console.WriteLine(sentence.Substring(0, 1));

Answer

If you must use Substring, then replace your loop by this

for (int i = 0; i < sentence.Length; i++)
{
    if (sentence.Substring(i, 1) == "z")
    {
        total++;
    }
}

And if you need to both count uppercase and lowercase z, then use following code

for (int i = 0; i < sentence.Length; i++)
{
    if (string.Equals(sentence.Substring(i, 1), "z", StringComparison.OrdinalIgnoreCase))
    {
        total++;
    }
}