如果字符不在char数组中,请使用“#”切换字符串中的字母

时间:2019-01-28 19:20:52

标签: c++ arrays function char

void funOne(char a[], string b, int aL, int bL) {
    int cnt[aL]={0};
    for(int i=0; i<bL; i++) {
        for(int j=0; j<aL; j++) {
            if((char)b[i]==a[j]; {
                cnt[j]++;
                break;
            }
        }
    }
    for(int i=0; i<bL; i++) {
        for(int j=0; j<aL; j++) {
            if((char)b[i]==a[j]&&cnt=0) {
                b[i]='#';
                break;
            }
        }
    }

有一个字符arr[]={'H', 't', 'h', 's', 'e', 'i'};和一个字符串"Sherlock Holmes is a fiction private detective"。字符串中不存在的每个字符都应替换为字符串中的"#"

输出应为

"She##### H###es is # #i#ti#n ##i##te #ete#ti#e"

我的代码有问题,但我不知道什么。

2 个答案:

答案 0 :(得分:1)

如果您正在寻找解决此问题的最佳解决方案,请查看! :) 想法是散列数组中的所有字符,然后在每次遍历输入字符串时检查其成员身份(检查-O(1))。

arr = set(['H', 't', 'h', 's', 'e', 'i'])
arr.add(' ') #so that whitespaces don't get replaced
input = 'Sherlock Holmes'
output = str()
for char in input:
    if char not in arr:
        output += '#'
    else:
        output += char

print output

此代码运行时间为O(n),但空间为O(n)。

答案 1 :(得分:0)

您的代码有很多错误,而且不必要复杂。可以简化为以下形式:

void funOne(char a[], int aL, string &b) {
    for(size_t i = 0; i < b.length(); ++i) {
        if (b[i] == ' ') continue;
        // check for other punctuation chars as needed... 
        bool found = false;
        for(int j = 0; j < aL; ++j) {
            if (b[i] == a[j]) {
                found = true;
                break;
            }
        }
        if (!found) b[i] = '#';
    }
}

使用标准std::find()算法可以进一步简化以下操作:

#include <algorithm>

void funOne(char a[], int aL, string &b) {
    char *aEnd = a + aL;
    for(size_t i = 0; i < b.length(); ++i) {
        if (b[i] == ' ') continue;
        // check for other punctuation chars as needed... 
        if (std::find(a, aEnd, b[i]) == aEnd) b[i] = '#';
    }
}

或者,通过使用std::string::find_first_not_of()方法:

void funOne(char a[], int aL, string &b) {
    for(size_t i = b.find_first_not_of(a, 0, aL);
        i != string::npos;
        i = b.find_first_not_of(a, i + 1, aL))
    {
        if (b[i] == ' ') continue;
        // check for other punctuation chars as needed... 
        b[i] = '#';
    }
}