【问题标题】:Concatenate a 'space' to the end of an array将“空格”连接到数组的末尾
【发布时间】:2013-06-22 14:11:34
【问题描述】:

我正在编写一个代码,如果我的数组不以空格结尾,则代码的行为会有所不同。我想检查最后是否有空格。如果没有,那么我想在数组的末尾附加一个空格。这是数组的代码。

char* buffer[1024];
fgets(buffer,1024,fp);
char* str = buffer+2; // don't need the first two characters
char* pch;
pch = strtok(str," ");//I am dividing the string into tokens as i need to save each word in a separate variable
.
.
.

所以我的问题是,首先,我如何检查str 的最后一个字符是否是空格? 二、如果不是空格,怎么追加空格?

我已经尝试过strcat,但我认为问题是我仍然不知道如何知道最后一个字符是否为空格。我知道这一切都可以通过字符串和向量轻松完成。但我想要我的代码的解决方案。谢谢!

编辑: 下面是分行和统计字数的代码。

//At the end of this while loop. ncol will contain the number of columns 
while(1){
fgets(buffer,1024,fp);
if (buffer[1] == 'C'){ // the line is #C 1 2 3 4 5 6 7 8 9 10 11 12 13
    char* str = buffer+2;

int n = strlen( str );
if(n == 0 || str[n-1] != ' ') {
str[n] = ' ';
str[n+1] = '\0';
}

  char* pch;
  pch = strtok(str," ");
  while(pch != NULL){
      ncol++;
      pch = strtok (NULL, " ");

    }
} 
if(buffer[0] == '#'){
    numHeader++;
    }
    else {break;}

}

【问题讨论】:

  • 你问的真的是 c++。这看起来像普通的 c。
  • 由于您反对在此处使用任何 C++ 功能,即使它们是当前问题形式的解决方案,我将在此问题上将 c++ 替换为 c。停止滥用标签。
  • 如果是strtok,我认为strtok(str, " \n")更好。

标签: c char append arrays


【解决方案1】:

既然你用 C++ 标记了你的问题:

std::string str = "bla ";
if (str[str.size()-1] != ' ')
    str.push_back(' ');
else
    //do smth

【讨论】:

  • 如我所说,我不想使用字符串。
  • 它是完全有效的 c++。
【解决方案2】:

这是您特定案例的代码

int n = strlen(str);
// *** RTRIM()
int idx = n-1;
for(; idx >= 0; idx--)
    if(str[idx] != '\0' && str[idx] != " " && str[idx] != '\t' && str[idx] != '\n' && str[idx] != '\r') 
        break;
str[idx + 1] = '\0';
// ***
int cnt = 0;
char* pch = strtok(str, " ");
while (pch != NULL)
{
    cnt++;
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
}

编辑使用右侧修剪

【讨论】:

  • 为了迂腐,我们应该检查n < 1023
  • @Emmet - “技术上正确”是最好的正确类型,已编辑。
  • @LastCoder 有趣的是,我使用的是相同的代码。但是在我的数组“缓冲区”末尾没有空格,我得到 cnt=13,如果有空格,它是 cnt=14。真的很感激这个解决方案。我不能使用字符串或其他选项的原因是因为我必须与其余代码保持一致。如果我在这里使用字符串,那么我必须更改很多其他的东西,这比现在的问题更大。
  • @detraveller - 您必须向我们展示您的整个功能代码,否则无法知道哪里出了问题。也许这是一个小的逻辑错误,也许您使用了“buffer”变量而不是“str”变量。
  • @detraveller - 我想我现在看到了你的问题“#C 1”当你做 buffer+2 时注意 C 和 1 之间的空间你的字符串将是“1”这个额外的空间在开头是为什么你从 strtok 得到一个额外的指针。试试 buffer+3,不要费心在最后添加额外的空格
猜你喜欢
  • 2021-08-30
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2011-04-26
相关资源
最近更新 更多