创建带有前导空格的字符串数组

标签 c arrays string

有没有一种方法可以初始化一个空字符串数组,然后请求用户输入,该输入将保存到字符串数组中,如果输入较小,则保留空的前导空格。 我计划使用更长的字符串数组和附加空格,以便我可以进行就地字符替换。 例如:

char foo[25];
scanf(%s,foo);
foo = this is a test"
print foo; 

结果如下:

"this is a test      "

最佳答案

您的问题不一致,您询问前导空格,但您的示例显示尾随空格。如果你的意思是尾随空白,你可以这样做:

#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 25

int main() {

    char string[BUFFER_SIZE];
    memset(string, ' ', BUFFER_SIZE - 1); // initialize with spaces
    string[BUFFER_SIZE - 1] = '\0'; // terminate properly

    if (fgets(string, BUFFER_SIZE, stdin) != NULL) {

        size_t length = strlen(string);

        string[length - 1] = ' '; // replace the newline \n

        if (length < BUFFER_SIZE - 1) {
            string[length] = ' ';  // replace extra '\0' as needed
        }

        printf("'%s'\n", string); // extra single quotes to visualize length
    }

    return 0;
}

使用

> ./a.out
this is a test
'this is a test          '
> 

添加单引号只是为了让您实际上可以看到空格被保留。 @BLUEPIXY 的方法非常有意义,只不过它会在您特别询问保留现有空格的输入中附加新的空格。

如果您想保留前导空格,也可以这样做。

关于创建带有前导空格的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553120/

相关文章:

javascript - 解析包含日期的 JSON 字符串时出现问题

java - 如何在 Java 中添加 vector 作为值

sql - 如何在 SQL 中使用单引号作为字符串的一部分

C 程序强制我有返回类型,但我不需要它。!

c++ - 流到字节数组

c - 如何将 G.726 ADPCM 信号转换为 PCM 信号?

time_t 的 C 字符串表示

ruby CSV : ignoring empty column

c - 当我们使用 %d 扫描字符时会发生什么?

c - 我的 int isMember() 上的循环函数