将 'space' 连接到数组的末尾

标签 c char append arrays

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

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 但我认为问题是我仍然无法弄清楚如何知道最后一个字符是否为空格。我知道这一切都可以用字符串和 vector 轻松完成。但我想要一个解决我的代码的方法。谢谢!

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

//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;}

}

最佳答案

这是您的具体案例的代码

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, " ");
}

编辑使用右侧修剪

关于将 'space' 连接到数组的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303115/

相关文章:

c - 如何打印结构并对其进行 memcpy?

c++ - 每个对象内存分配的开销是多少?

Python:合并具有不同标题的csv数据

c++ - 字符串到字符数组不起作用

创建动态字符数组

java - 确定在列表末尾 append 值的复杂性

jquery - 当已经在脚本中时,如何使用 jQuery 将脚本写入页面

c++ - _strrev 运行方式

尽管具有相同的值,但在 Arduino 中使用 C 控制电机的速度会导致不同的速度

c - 在 c 中重新分配 char ** 的内存