从 C 样式字符串中删除子字符串 "in place" 在C++代码中
Remove substrings from a C-style string "in place" in C++ code
>我有一个面试任务,在不使用字符串函数或额外内存的情况下从当前字符串中删除子字符串......我只尝试了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;
}
相关文章:
- 编译包含字符串的代码时遇到问题
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 我无法在 qt 的C++代码中定义字符串
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 有人可以解释一下这段代码如何能够反转字符串
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 如何用符合C++核心准则的代码替换C风格的字符串解析
- C++/CLI访问字符串::来自非CLI代码的格式
- MSVC UTF8字符串编码使用了不正确的代码点
- C++指向对象的指针堆数组中,如何将字符串传递给特定对象?有一些代码请看一下:
- 将浮点数转换为字符串时如何加快此代码的速度?
- C++代码,用于在用户插入的字符串的每个元音之后插入一对字符
- 如何获取包含 NULL 字符的外壳代码字符串的长度
- 字符串代码不起作用
- C++字符串代码点和代码单元的任何良好解决方案
- 输入验证,需要数字,而不是字符串.代码导致无限循环
- 使用引用传递方法的反向字符串代码不起作用
- 这个反向字符串代码正确吗