使用指针替换cpp中字符串中的字符

时间:2016-07-07 07:06:20

标签: c++ arrays string pointers

我是cpp的新手,并尝试用'!'替换第二次出现'*'使用以下方法在给定字符串中使用char。

#include <iostream>
#include <string.h>

using namespace std;

void replaceChar(char **inp){
    char *tmp = *inp;
    const char *c = "*";
    char *cmark = strstr(tmp,c);
    cout<< *cmark;
    if(cmark != NULL && strlen(cmark) > 1){
        cmark++;
        if(strstr(cmark,c)){
            int len = strlen(cmark);
            cout<<"len"<<len;
            for(int i=0;i<len;i++){
                if(cmark[i] == '*'){
                    cout<<"i.."<<i;

                    cmark[i] = '!';//error point
                }
            }
        }
    }

}


int main() {

    char * val = "this is string*replace next * with ! and print";
    replaceChar(&val);
    cout<<"val is "<< val;
    return 0;
}

我在error point行上遇到运行时错误。如果我注释掉这一行,我会得到正确的'*'索引。 是否可以使用'*'替换'!' cmark[i] = '!'

2 个答案:

答案 0 :(得分:1)

选中此difference between char s[] and char *s in C

#include <iostream>
#include <string.h>

using namespace std;

void replaceChar(char *inp){
    char *tmp = inp;
    const char *c = "*";
    char *cmark = strstr(tmp,c);
    cout<< *cmark;
    if(cmark != NULL && strlen(cmark) > 1){
        cmark++;
        if(strstr(cmark,c)){
            int len = strlen(cmark);
            cout<<"len"<<len;
            for(int i=0;i<len;i++){
                if(cmark[i] == '*'){
                    cout<<"i.."<<i;

                    cmark[i] = '!';
                }
            }
        }
    }

}


int main() {

    char val[] = "this is string*replace next * with ! and print";
    replaceChar(val);
    cout<<"val is "<< val;
    return 0;
}

答案 1 :(得分:0)

无需在方法中将指针传递给指针。 相反,您可以将原始指针传递给字符串。 你可以用更简单的方式做到这一点。

void replaceChar(char *inp){
    int i;
    int second = 0;
    /* Strings in C\C++ is null-terminated so we use it to determine 
    end of string */
    for (i = 0; inp[i] != '\0'; ++i) {
        if (inp[i] == '*') {
            /* Use flag to determine second occurrence of * */
            if (!second) {
                second = 1;
            } else {
                inp[i] = '!';
                break;
            }
        }
    }
}