如何从 CPP 中的字符串(文件名)中只删除一个连字符(第一次出现)?
how to remove only one hyphen (first occurance) from the string(file name) in CPP?
如何从 CPP 中的字符串(文件名)中只删除一个连字符(第一次出现)?假设我有文件名 DS-NMDX-2C219-FK。假设我只想删除第一个连字符?在 DS-NMDX 之间 ?
你需要先找到它,使用find(必须#include ):
int find = str.find("-");
这将在 int "find" 中存储第一次出现“-”的位置。
然后,您可以执行以下操作:
str.erase(find,1);
这从位置 find 开始擦除并擦除一个位置。
工作代码:
int main() {
string str = "DS-NMDX-2C219-FK";
int finder = str.find("-"); // find the position of -
str.erase(finder,1); // start at position of -, erase one position
cout << str << endl;
return 0;
}
David 的回答基本上是正确的,但我们还需要添加保护以保持代码在所有可能的输入中正常工作,因为在输入字符串中可能找不到“-”。
示例代码如下:
int main(int argc, char *argv[])
{
std::string input = "DS-NMDX-2C219-FK";
// .find return the position of first occurence of '-'
auto pos = input.find('-');
// '-' might not exist in input, so need protection here
if (pos != std::string::npos) {
input.erase(pos, 1);
}
std::cout << input << std::endl;
return 0;
}
string s = 'DS-NMDX-2C219-FK';
cout<< s.erase(s.find('-'),1);
如何从 CPP 中的字符串(文件名)中只删除一个连字符(第一次出现)?假设我有文件名 DS-NMDX-2C219-FK。假设我只想删除第一个连字符?在 DS-NMDX 之间 ?
你需要先找到它,使用find(必须#include
int find = str.find("-");
这将在 int "find" 中存储第一次出现“-”的位置。
然后,您可以执行以下操作:
str.erase(find,1);
这从位置 find 开始擦除并擦除一个位置。
工作代码:
int main() {
string str = "DS-NMDX-2C219-FK";
int finder = str.find("-"); // find the position of -
str.erase(finder,1); // start at position of -, erase one position
cout << str << endl;
return 0;
}
David 的回答基本上是正确的,但我们还需要添加保护以保持代码在所有可能的输入中正常工作,因为在输入字符串中可能找不到“-”。
示例代码如下:
int main(int argc, char *argv[])
{
std::string input = "DS-NMDX-2C219-FK";
// .find return the position of first occurence of '-'
auto pos = input.find('-');
// '-' might not exist in input, so need protection here
if (pos != std::string::npos) {
input.erase(pos, 1);
}
std::cout << input << std::endl;
return 0;
}
string s = 'DS-NMDX-2C219-FK';
cout<< s.erase(s.find('-'),1);