基本上我有一个由多个单词组成的字符串,如下所示:"Hello world test"
。
如果我尝试用这样的结构打印它
printf("%s", string);
或者像这样
for (int i = 0; i < strlen(string); ++i) {
printf("%c", string[i];
}
我总是得到这样的输出:Hello world
我得到的 strlen 也是 11 而不是 16。
如果我尝试使用之前计算字符串中单个字符的 int 计数器打印出完全相同的字符串
for (int i = 0; i < counter; ++i) {
printf("%c", string[i];
}
我实际上得到了正确的输出 Hello world test
,这导致我相信元素在字符串中被正确分配,但由于某种原因 %s 和 strlen 只是忽略了最后一个空格之后的元素.
为什么会这样?到底是怎么回事?我该如何解决这个问题?
编辑:
请求的实际代码:
#include <stdio.h>
#include <string.h>
typedef int BOOL;
#define TRUE 1
#define FALSE 0
int main() {
char sentence[64] = " ", reversal[64] = " ", reversal_copy[64] = " ";
int index = 0, counter = 0;
BOOL reset = TRUE, last_cycle = FALSE;
printf("Enter a sentence: ");
for (int i = 0; sentence[strlen(sentence) - 1] != '\n'; i++) {
scanf("%c", &sentence[i]);
}
/* Copies the input in a string reversing it */
for (int h = strlen(sentence) - 2, k = 0; h >= 0; h--, k++) {
reversal[k] = sentence[h];
}
/* Detects the first character of a word and the last character of the same word before a space,
switching the first char with the last, the second with the pre-last and so on*/
for (int i = 0; i < strlen(reversal); i++) {
if (reset == TRUE) {
index = i;
reset = FALSE;
}
if (i == strlen(reversal) - 1) {
last_cycle = TRUE;
counter++;
}
if (reversal[i] != ' ') {
counter++;
if (last_cycle == TRUE) {
goto reversing;
}
}
else {
reversing:
for (int h = index, z = counter; h < counter; h++, z--) {
reversal_copy[h] = reversal[z - 1];
reversal_copy[z - 1] = reversal[h];
}
if (last_cycle == FALSE) {
reversal_copy[i] = ' ';
}
reset = TRUE;
counter++;
}
}
printf("%lu ", strlen(reversal_copy));
for (int i = 0; i < counter; i++) {
printf("%c", reversal_copy[i]);
}
printf("%s\n\n", reversal_copy);
return 0;
}
最佳答案
如果 strlen()
返回 11,那么您在世界“world”之后有一个 \0
字符。
strlen
和 printf
都通过使用 0 终止符来确定“什么是字符串”,因此它们的行为相同也就不足为奇了。
关于c - 为什么 strlen() 不代表我的字符串的实际长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548720/