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

Replacing character in string in cpp using pointer

本文关键字:字符串 字符 cpp 指针 替换      更新时间:2023-10-16

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

#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] = '!''*'替换为'!'

检查 C 语言中 char s[] 和 char *s 之间的区别

#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;
}

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

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