Strong password (String problem) in C++
In this tutorial, we will solve the strong password problem in C++ which will have certain mentioned constraints. Let us define our constraints then we will solve the problem.
- Its length should be at least 6.
- Must contain at least one digit.
- There should be at least one lowercase English character.
- It is going to contain at least one uppercase character.
- It should contain at least one special character. The special characters can be: !@#$%^&*()-+
Now we will be given a string of a particular length and we will have to find how many more characters are required to make the password strong.
To solve this problem we have to use multiple if-else conditions. In each condition, we have to mention the required condition to get the answer.
For example:
If the password is Codespeedy.
Then it is easy to note that the length of the password is greater than 6 but it doesn’t contain any special character. Neither it contains any digit. So the minimum character required to make it a strong password will be 2. Let move to our coding part in which we will mention different condition to solve this problem.
Program to Strong password problem
CPP source code:
// Program to solve strong password problem #include<bits/stdc++.h> using namespace std; int minimumNumber(int n, string password) { // Returning the minimum number of characters // to make the password strong int a=0,b=0,c=0,d=0; for(int i=0;i<n;i++) { if(password[i]=='!' || password[i]=='@' ||password[i]=='#'|| password[i]=='$' || password[i]=='%' || password[i]=='^' || password[i]=='&' || password[i]=='*' || password[i]=='(' || password[i]==')' || password[i]=='-' || password[i]=='+') { a=1; } else if(password[i]-64>0 && password[i]-64<=26) { b=1; } else if(password[i]-96>0 && password[i]-96<=26) { c=1; } else if(password[i]-48>=0 && password[i]-48<=9) { d=1; } } int sum=a+b+c+d; if(n<=3) { return (6-n); } else if((n==4 && sum==1)|| (n==5 and sum ==1)) { return 3; } else if((n==4 && sum==2)|| (n==5 and sum ==2)) { return 2; } else if((n==4 && sum==3)||(n==4 && sum==4)) { return 2; } else if((n==5 && sum==3) || (n==5 && sum==4)) { return 1; } else if(n>=6 && sum==1) { return 3; } else if(n>=6 && sum==2) { return 2; } else if(n>=6 && sum==3) { return 1; } else{ return 0; } } // Driver Code int main() { int n; cout<<"Enter the length of password: "; cin>>n; string password; cout<<"\nEnter the password: "; cin>>password; cout<<"\nMinimum character required to make it a strong password is " <<minimumNumber(n,password); return 0; }
Input/Output:
Enter the length of password: 10 Enter the password: Codespeedy Minimum character required to make it a strong password is 2
You may also learn:
Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.
Leave a Reply