C++ 中移除禁用字符的函数


讨论如何移除函数,这些函数将移除字符串中禁止的字符,例如 [ ‘ : ’, ‘ ? ‘, ‘ \ ’, ‘ / ’, ‘ < ’, ‘ > ’, ‘ | ’, ‘ * ’ ]

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 '/':
            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;
}

输出

Hello, Welcome to Tutorials point.

上述代码的解释

  • 在遍历字符串时使用 switch case,其中字符串的每个元素都与 case 字符进行检查。

  • 如果字符等于 case 字符,则将其替换为空字符。

结论

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

我们还讨论了此问题的 C++ 程序,我们也可以使用 C、Java、Python 等编程语言来实现。希望本教程对您有所帮助。

更新于: 2021年11月26日

221 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.