【问题标题】:C++ How to remove double quotes in charC ++如何删除char中的双引号
【发布时间】:2014-01-26 12:35:00
【问题描述】:

我想从字符串中删除双引号,例如 13.3" Rentina 变为 13.3 Rentina

const char* s = sheet->readStr(row, col);
int ii = strlen(s);
char* b;
b=(char*)s;

char ch;
for (int i = 0; i < ii ;++i) {
  strncpy(&ch, b+ii, 1);
  if(ch == '\"'){
    ch = '\"';
    memcpy(b+i, &ch, 1);
  }
}

myfile << b;

【问题讨论】:

  • 你能澄清你的问题吗?
  • 你的代码有什么问题?
  • 你到底想做什么?
  • 你可以尝试使用 std::string::replace
  • 您的描述看起来更像是您想删除引号,而不是替换它们(除非您的意思是用空格替换它们)。

标签: c++ replace char


【解决方案1】:

如果您在 C++ 中处理字符串,则应仅在有充分理由使用字符数组和函数(如 strncpy)时使用它们。默认情况下,您应该使用标准字符串,例如内存管理更容易。 std::string 问题的解决方案是

std::string s = sheet->readStr(row, col);  
size_t pos = 0;
while ((pos = s.find('"', pos)) != std::string::npos)
    s = s.erase(pos, 1);
myfile << s;

【讨论】:

  • 谢谢!!这是工作。但编码有问题。例如我在 utf-8 中的记录。当我得到结果 "TT","TГЄn sбєЈn phбє","Bб»™ vi xб» lГ。你能帮我吗!!非常感谢你
【解决方案2】:

你不能这样做b=(char*)s!!!

编译器允许你使用这个,但是一旦你尝试写入b指向的内存地址空间,你就会得到一个运行时异常。

变量s可能指向代码段中的一个地址,这是您程序中的只读内存地址空间(“可能”,因为可能const s 的声明只是您主动添加的内容。

您应该分配一个新的char 数组,并将输出字符串复制到该数组中。

所以首先把上面的语句改成b = (char*)malloc(strlen(s))

此外,不要将char 变量的地址传递给strncpy(或任何其他str 函数)。这些函数对char 数组进行操作,或者假设数组以 0 字符结尾,或者将数组末尾的字符设置为 0。

你可以试试下面这段代码(假设你的目的是删除'"'):

const char* s = sheet->readStr(row, col);
int ii = strlen(s);
char* b = (char*)malloc(ii+1);
if (b != NULL)
{
    int i,j;
    for(i=0,j=0; i<ii; i++)
    {
        if (s[i] != '"')
            b[j++] = s[i];
    }
    b[j] = 0;
    // Add your code here (do whatever you wanna do with 'b')
    free(b);
}
else
{
    printf("Out of memory\n");
}

【讨论】:

  • "你不能做 b=(char*)s!!!" - 实际上这取决于sheet-&gt;readStr(row, col); 返回的内容。如果它返回一个指向可写空间的指针,那么通过b写入该空间是非常好的,如果地址转换为const char *然后在此期间返回char *,则无关紧要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2018-12-15
  • 2023-03-19
  • 2020-07-10
  • 1970-01-01
  • 2017-11-20
相关资源
最近更新 更多