c - 为什么 strlen() 不代表我的字符串的实际长度?

标签 c

基本上我有一个由多个单词组成的字符串,如下所示:"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 字符。

strlenprintf 都通过使用 0 终止符来确定“什么是字符串”,因此它们的行为相同也就不足为奇了。

关于c - 为什么 strlen() 不代表我的字符串的实际长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548720/

相关文章:

c - 如何比较表格

c - C中的结构,检查点是否在圆圈内

C程序,使用函数读取用户输入的数组元素,然后交换它们

c - C 中的字符串标记化和 strstr - 段错误

c - ruby FFI : multi-dimensional array

c - openssl api验证公钥与私钥匹配

在 Windows XP 中编译 C

c - 为什么我在这里遇到段错误?需要帮忙。想要将整数放入 char 指针数组

c - 为什么 int_fast16_t 在 64 位系统上是 64 位?

c - while循环和算术运算符