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

问题描述:

有没有一种方法可以初始化一个空字符串数组,然后再请求来自用户的输入保存到字符串数组中,如果输入较小,则留下空的前导空格。 我打算使用一个更长的字符串数组和空格,这样我就可以进行字符替换。 例如:创建带前导空格的字符串数组

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

结果是这样的:

"this is a test  " 
+0

您的问题已经解决http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way – denis

+3

http://ideone.com/ lJaJnJ – BLUEPIXY

+0

@BLUEPIXY我在开始时看到双引号,最后我该如何摆脱这些?我原本从不想要他们 – Fenomatik

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

#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的方法非常有意义,只是它将新的空白添加到输入,您特别询问了有关保留现有空白的输入。

如果您想保留领先的空格,那么也可以这样做。