从 C++ 中的字符数组中删除字符
Removing chars from an array of chars in C++
我正在尝试创建一种从字符串中删除子字符串的方法。它是 char 形式,所以我不能使用方便的方式来愉快地给字符串。我知道如何搜索它,我可以找到索引,但是删除一个字符对我来说有点冒险。如果有人有任何想法,我将不胜感激。谢谢
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
char str[20];
char del[20];
char * delStorage;
char select(char);
int main()
{
cout << "Enter a string to the console." << endl;
cin >> str;
cout << "You inputted " << str << " for the string." << endl;
select(letter);
return 0;
}
char select(char letter)
{
cout << "Enter one of the following commands d for delete." << endl;
cin >> letter;
switch (letter)
{
case 'D':
case 'd':
cout << "Enter a string to delete." << endl;
cin >> del;
delStorage = strstr(str, del);
if (delStorage)
{
cout << del << " has been found. Deleting..." << endl;
delStorage.Replace(str, del, "");
}
break;
}
我无法使用 Replace 方法,因为它是字符。我尝试了嵌套循环,但由于 char
和 int
的不兼容而卡住了。如果有人有建议,我会洗耳恭听。再次感谢 Stack 社区。
不是一个完整的答案,因为这看起来像是您想要自己解决的家庭作业问题。这是一个使用低级指针的解决方案,但您可以调整它以使用迭代器。
保留一个左指针和一个右指针。右指针应该是const char *
。当您遍历字符串时,如果您看到子字符串的可能开头,请增加右指针而不是左指针。如果结果不是子串(fog
,不是foo
),则将左指针设置为右指针,继续查找。如果它是子字符串,则复制从右指针开始的字符串,现在是子字符串末尾后的字符串,越过子字符串,到左指针标记的位置。如果到达字符串的末尾,请停止。
我正在尝试创建一种从字符串中删除子字符串的方法。它是 char 形式,所以我不能使用方便的方式来愉快地给字符串。我知道如何搜索它,我可以找到索引,但是删除一个字符对我来说有点冒险。如果有人有任何想法,我将不胜感激。谢谢
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
char str[20];
char del[20];
char * delStorage;
char select(char);
int main()
{
cout << "Enter a string to the console." << endl;
cin >> str;
cout << "You inputted " << str << " for the string." << endl;
select(letter);
return 0;
}
char select(char letter)
{
cout << "Enter one of the following commands d for delete." << endl;
cin >> letter;
switch (letter)
{
case 'D':
case 'd':
cout << "Enter a string to delete." << endl;
cin >> del;
delStorage = strstr(str, del);
if (delStorage)
{
cout << del << " has been found. Deleting..." << endl;
delStorage.Replace(str, del, "");
}
break;
}
我无法使用 Replace 方法,因为它是字符。我尝试了嵌套循环,但由于 char
和 int
的不兼容而卡住了。如果有人有建议,我会洗耳恭听。再次感谢 Stack 社区。
不是一个完整的答案,因为这看起来像是您想要自己解决的家庭作业问题。这是一个使用低级指针的解决方案,但您可以调整它以使用迭代器。
保留一个左指针和一个右指针。右指针应该是const char *
。当您遍历字符串时,如果您看到子字符串的可能开头,请增加右指针而不是左指针。如果结果不是子串(fog
,不是foo
),则将左指针设置为右指针,继续查找。如果它是子字符串,则复制从右指针开始的字符串,现在是子字符串末尾后的字符串,越过子字符串,到左指针标记的位置。如果到达字符串的末尾,请停止。