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