卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

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

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 '/':
            case '':
            case ':':
            case '?':
            case '"':
            case '<':
            case '>':
            case '|':
            case '*':
            // inserting null value in place of forbidden characters.
            str[j] = '';
            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等编程语言来实现。希望您会发现本教程有帮助。

卓越飞翔博客
上一篇: 百度AI接口与Golang:实现情感分析,让应用更加智能
下一篇: 从零开始学习Golang对接百度AI接口,教程来了!
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏