从 C 样式字符串中删除子字符串 "in place" 在C++代码中

Remove substrings from a C-style string "in place" in C++ code

本文关键字:字符串 代码 place C++ in 样式 删除      更新时间:2023-10-16

>我有一个面试任务,在不使用字符串函数或额外内存的情况下从当前字符串中删除子字符串......我只尝试了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 函数只是将源字符串的开头与子字符串进行比较,并返回源(如果它不是以子字符串开头
  • (或源加上子字符串的长度(如果它以子字符串开头(。

演示

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

字符串函数的存在是有原因的。 如果你不使用它们,你能从头开始创建它们吗?

如果是这样,这是我解决问题的方法。 编写具有 const 要求的自定义字符串函数非常有教育意义。

如评论中所述,除非可以修改传入的字符串,否则这将不起作用,因此我将其设置为非常量字符串。

让我知道这是否符合面试挑战:

#include <iostream>
bool myStrnCmp(char *str1, const char *str2, int len) {
char *cptr1 = (char *) str1;
char *cptr2 = (char *) str2;
for (int i = 0; i < len; i++) {
if (*(cptr1 + i) != *(cptr2 + i))
return false;
}
return true;
}
int mystrlen(const char* str) {
int i = 0;
while(*(str + i) != '')
i++;
return i;
}
int findSubStr(char *str, const char *substr) {
int position = 0;
int len = mystrlen(substr);
while(*(str + position) != '') {
for (int i = 0; i < len; i++) {
if (myStrnCmp(str + position + i, substr, len))
return position + i;
}
++position;
}
return -1;
}
void myStrCpy(char *str, const char *substr) {
memmove(str, substr, mystrlen(substr) + 1);
}
void removeSubstr(char *str, const char *substr) {
int position = findSubStr(str, substr);
while(position >= 0) {
myStrCpy(str + position, str+position+mystrlen(substr));
position = findSubStr(str, substr);
}
}

int main() {
char str[]{"this that there"};
char* substr = "th";
removeSubstr(str,substr);
std::cout<<str;  //should be now "is at ere"
return 0;
}