E
E
evans_852020-11-02 12:13:42
C++ / C#
evans_85, 2020-11-02 12:13:42

How to use a variable of type char?

How to remove a char variable from an array for viewing in a loop?

string password = Console.ReadLine();
char[] notAllowedSymbols = { '!', '#', '$', '%', '&', '(', ')', '*', ',', '+', '-' };

for (int i = 0; i < notAllowedSymbols; i++)
{
    if (i.Contains(notAllowedSymbols))
        break;
    Console.WriteLine("Invalid");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Foggy Finder, 2020-11-02
@evans_85

Let's try to figure it out.
An array is a limited set of some data of a particular type.

char[] notAllowedSymbols = { '!', '#', '$', '%', '&', '(', ')', '*', ',', '+', '-' };

here, you have declared an array of elements of type char .
Indexes are used to access a value in an array.
The first element in the array is available at index 0.
The second is at index 1.
and so on.
You can easily see that the index here is essentially just a serial number shifted by one.
Now back to our notAllowedSymbols array .
How now, given the information about the indexes, to get access to some element? C# has indexers for this:
array[index]

so to get the first element you need to write exactly the same way you can get any other element by specifying the correct index ( [i] ). Now, as for the above part of the code: the message is absolutely correct - as soon as we are convinced that the string contains a forbidden character, we need to stop the execution and inform the user about the error. But the implementation is not entirely accurate - break will interrupt the execution of the loop and the user will never know that he made an inaccuracy. This is where functions come in handy. Let's check separately. Its result can be either "passed successfully" or "contains errors". There are only two values. So, here it is convenient to use the bool type . True
var firstChar = notAllowedSymbols[0]; // '!'
Now the implementation itself
private static bool IsValid(string password)
{
    char[] notAllowedSymbols = { '!', '#', '$', '%', '&', '(', ')', '*', ',', '+', '-' };

    for (int i = 0; i < notAllowedSymbols.Length; i++)
    {
        if (password.Contains(notAllowedSymbols[i]))
        {
            return false;
        }
    }
    return true;
}

O
oleg_ods, 2020-11-02
@oleg_ods

1. i is an integer (int) and notAllowedSymbols is an array. In the condition of the for loop, you are comparing a number with an array. You can not do it this way. You need to compare the number with the length of the array.
2. In the if condition, you check that i (which is an integer) contains an array of characters. How can a number contain symbols? Apparently you need to check whether the password string contains a character from the notAllowedSymbols array with index i.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question