c - 删除字符串中所有出现的子字符串
问题描述
该函数接收一个字符串和一个子字符串,并应删除字符串中所有出现的该子字符串。例如,
string = hello world
substring = hello
该函数应该只打印“ world
”
我应该指出,我必须只使用指针来解决这个问题。
我已经尝试过了,但它只删除了子字符串第一个字母的出现。
char* del_all_substr(char *pstr, char *psub){
char *pr = pstr;
char *pw = pstr;
while (*pr){
for (int i = 0; i <strlen(psub);i++) {
*pw = *pr++;
pw += (*pw != *(psub+i));
}
*pw = '\0';
}
}
int main_tp06(int argc, const char *argv[]){
char str[] = "hello world";
char sub[] = "hello";
del_all_substr(str,sub);
printf("%s",str);
return 0 ;
}
解决方案
you could use strstr
repeatedly to find all occurrences of the string. For example consider this string "Hello world, Hello world"
, and say that we want to move all occurrences of "Hello"
from the string. You can use strstr
to find the first instance of "Hello"
, after that you can overwrite it by moving everything in the string back using memmove (make sure you move the nul terminator as well), repeat again and again until strstr
returns no matches. You could also avoid this approach by instead allocating your own string that is at least strlen(pstr)
bytes long and then copying data from pstr
byte by byte and not copying the bytes that match psub
推荐阅读
- php - 我的自动回复功能不起作用可能是什么问题?
- pyspark - pyspark 中的 log4j 自定义字段
- excel - 我需要在 SharePoint 上的 2 个工作簿之间建立连接
- amazon-web-services - 存储从 AWS SES 发送的电子邮件
- vba - 如何在exel的选定列中查找特定单词
- sql - 用于计数记录的 SQL 查询,其中 count = 1 且 Value <50
- android - 如何检查用户是否为我的应用阻止了互联网?
- javascript - Vite / Vue 3 : "require is not defined" when using image source as props
- node.js - Socket.io/Ws 事件无法正常工作
- excel - 对象在更改标签标题时不支持此属性或方法(错误 438)