gpt4 book ai didi

c++ - 从 C++ 代码中的 C 风格字符串 "in place"中删除子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:20 26 4
gpt4 key购买 nike

我的面试任务是在不使用字符串函数或额外内存的情况下从当前字符串中删除子字符串...我只尝试使用 strlen 但没有找到改变它的方法。 ..

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
char * str = "this that there";
char * substr = "th";
removeSubstr(str,substr);
cout<<str; //should be now "is at ere"

return 0;
}
void removeSubstr(char * str, const char * substr){
}

最佳答案

  • 由于您从原始字符串中删除了字符,字符串正在收缩,因此您不需要额外的空间。您只需将字符从较高索引(源)复制到较低索引(目标)。
  • 如果源索引指向的位置以搜索到的子字符串开头,则必须跳过它。
  • skip 函数简单地将源字符串的开头与子字符串进行比较,并返回源(如果它不是以子字符串开头)或源加上子字符串的长度(如果它是以子字符串开头)。

Demo

#include <iostream>

char* skip_if( char* s, const char* ss )
{
char* p = s;
const char* pp = ss;
while( *p == *pp && *p )
p++, pp++;
return *pp ? s : p;
}

void remove( char* s, const char* ss )
{
char *ps = s; // source
char *pd = s; // destination
while( *ps )
{
ps = skip_if( ps, ss );
*pd++ = *ps++;
}
*pd = 0;
}

int main()
{
using namespace std;

char str[] = "this that there this that there";
const char* substr = "th";
remove( str, substr );

cout << str;

return 0;
}

关于c++ - 从 C++ 代码中的 C 风格字符串 "in place"中删除子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52972522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com