简体   繁体   中英

Printing array using printf with space between characters

This one is simple, I have an array of chars and I want to print it but I want to have a space between each individiual member of array, is this possible with printf? Or do I have to prepare a separate function?

Example:

char array[]="hello";
printf ("%s", array);

Output:

h e l l o

You can use this approach also to solve your task

 int main(){
    char array[]="hello";
    char *p=&array;
    while(*p) {
     printf("%c ",*p); 
       p++;
    }
    return 0;
}

Output

h e l l o

If you know the length of array,let it be n then

for(i=0;i<n;i++) printf("%c ",arr[i]);

Notice a whitespace ie ' ' is written after %c .This ensures a whitespace after every character from array is printed(whitespace will also be there after the last element). And if you dont know the length of array then you can use while loop with condition that array with end with null just while printing each element provide a space after %c .

Since you don't want an extra space after the final character:

char *tmp = array;
if (*tmp) {
    putchar(*tmp++);
    while (*tmp) {
        putchar(' ');
        putchar(*tmp++);
    }
}

Or turn it into a function:

void put_with_spaces(const char *s, FILE *fp)
{
    if (!*s)
        return;
    fputc(*s++, fp);
    while (*s) {
        fputc(' ', fp);
        fputc(*s++, fp);
    }
}

A new solution occurred to me as I was browsing this question

for (int i = 0; i < n; i++) {
    printf("%*c", 1 + !!i, arr[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM