
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function for Removing Forbidden Characters in C++
Discuss the way to remove functions that will remove forbidden characters like [ ‘ : ’, ‘ ? ‘, ‘ \ ’, ‘ / ’, ‘ < ’, ‘ > ’, ‘ | ’, ‘ * ’ ] from a string, for example
Input: str = “ Hello: Welco*me/ to Tu>torials point|. ” Output: “ Hello Welcome to Tutorials point. ” Explanation: Input String contains forbidden characters which got removed and new string has no forbidden characters. Input: str = “ How/ are y*ou doi,ng? ” Output: “ How are you doing ”
Approach to Find the Solution
A simple approach that can be applied to this problem is,
Traverse the string from any side.
Check for each character if it belongs to forbidden characters.
Remove the character if it belongs to forbidden characters.
We can either insert a null value or a new string to insert all the characters except forbidden in removing characters.
Example
C++ Code for the Above Approach
#include <stdio.h> #include <bits/stdc++.h> using namespace std; // function to remove forbidden charcters. void removeforbidden(char* str){ int j = 0; int n = strlen(str); // traversing through the string and searching for forbidden characters. for(int i = 0;i<n;i++){ switch(str[i]){ case '/': case '\': case ':': case '?': case '"': case '<': case '>': case '|': case '*': // inserting null value in place of forbidden characters. str[j] = '\0'; default: str[j++] = str[i]; } } // printing the string. for(int i = 0;i<n;i++) cout << str[i]; return; } int main(){ char str[] = "Hello: Welco*me/ to Tu>torial?s point|."; removeforbidden(str); return 0; }
Output
Hello, Welcome to Tutorials point.
Explanation of the Above Code
Switch case is used while traversing through the string in which each element of a string is checked with the case characters.
If a character equals the case character, then it is replaced by a null character.
Conclusion
In this tutorial, we discussed created a Function for removing forbidden characters like [ ‘ : ’, ‘ ? ‘, ‘ \ ’, ‘ / ’, ‘ < ’, ‘ > ’, ‘ | ’, ‘ * ’ ] We discussed a simple approach to solve this problem by traversing through the string and matching the characters with forbidden characters.
We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.