c++ - 从 C-Style 字符串 C++ 中删除字符

标签 c++ c arrays char cstring

我有一个 .txt 文件,看起来像这样......

City- Madrid
Colour- Red
Food- Tapas
Language
Rating

基本上,我想将 - 或行尾(空格)之前的所有内容添加到一个数组中,然后将所有内容添加到第二个数组中。

我的代码将 -whitespace 之前的所有内容都添加到一个数组中,但其余部分没有。

{
   char** city;
   char** other;
   city = new *char[5];
   other = new *char[5];
   for (int i=0; i<5; i++){
      city = new char[95];
      other = new char[95];
      getline(cityname, sizeof(cityname));
      for(int j=0; j<95; j++){
        if(city[j] == '-'){
             city[j] = city[95-j];
        }
        else{
             other[j] = city[j]; // Does not add the everything after - character
        }
      }
}

如果有人能帮助我处理 else 语句,我将不胜感激。

最佳答案

如果您要编写 C++ 代码,最简单的方法就是使用 std::string。这样:

std::string line;
std::getline(file, line);
size_t hyphen = line.find('-');
if (hyphen != std::string::npos) {
    std::string key = line.substr(0, hyphen);
    std::string value = line.substr(hyphen + 1);
}
else {
    // use all of line
}

如果你想坚持使用 C 风格的字符串,那么你应该使用 strchr:

getline(buffer, sizeof(buffer));
char* hyphen = strchr(buffer, hyphen);
if (hyphen) {
    // need key and value to be initialized somewhere
    // can't just assign into key since it'll be the whole string
    memcpy(key, buffer, hyphen); 
    strcpy(value, hyphen + 1);  
}
else {
    // use all of buffer
}

但真的更喜欢std::string

关于c++ - 从 C-Style 字符串 C++ 中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961715/

相关文章:

c++ - 构造函数段错误

c - 用于非均匀大小超球体中最近邻搜索的快速空间数据结构

c - 为什么我们在C中包含头文件

javascript - 什么是重新排列项目的好算法和数据结构?

java - 我的代码运行,但当我比较两个数组的内容时,if 语句没有打印其内容

c++ - 如何查看编译器生成的代码

c++ - 删除函数定义(编码标准)中未使用的参数名称。

c++ - OpenCV--如何从低质量的灰度图像中获得更好的手部轮廓?

c - LNK2005 在 .c 文件中包含 .h 文件时发生

PHP foreach 插入数组