Home  >  Article  >  Backend Development  >  Function to remove forbidden characters in C++

Function to remove forbidden characters in C++

WBOY
WBOYforward
2023-08-27 13:33:15544browse

Function to remove 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 ”

解决方案的方法

可以应用于此问题的简单方法是:

  • 从任一方向遍历字符串。

  • 检查每个字符是否属于禁止字符。

  • 如果字符属于禁止字符,则删除该字符。

  • 我们可以插入一个空值或新字符串,以插入除禁止字符外的所有字符。

示例

上述方法的C++代码

#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 &#39;/&#39;:
            case &#39;\&#39;:
            case &#39;:&#39;:
            case &#39;?&#39;:
            case &#39;"&#39;:
            case &#39;<&#39;:
            case &#39;>&#39;:
            case &#39;|&#39;:
            case &#39;*&#39;:
            // inserting null value in place of forbidden characters.
            str[j] = &#39;\0&#39;;
            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.

上述代码的解释

  • 在遍历字符串时,使用switch case语句来检查字符串的每个元素与case字符是否相等。

  • 如果字符与case字符相等,则将其替换为null字符。

结论

在本教程中,我们讨论了创建一个函数来删除禁止字符(如[ ‘ : ’, ‘ ? ‘, ‘ \ ’, ‘ / ’, ‘ ’, ‘ | ’, ‘ * ’ ])。我们讨论了一种简单的方法来解决这个问题,即通过遍历字符串并将字符与禁止字符进行匹配。

我们还讨论了用于解决这个问题的C++程序,我们可以使用C、Java、Python等编程语言来实现。希望您会发现本教程有帮助。

The above is the detailed content of Function to remove forbidden characters in C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete