TheBigDig
TheBigDig

Reputation: 49

Print a string char by char without spaces

In my homework problem, my instructor wants us to write a program that will print a string character by character on new lines but will ignore spaces and will print duplicate characters on the same line. So for example printing "Hello World" char by char would return

H
e
ll
o
W
o
r
l
d

I have been able to get my code to print a string character by character but I can't get it to print duplicates on the same line or ignore spaces. I have looked at some other similar questions and it seems like it is no trivial task.

#include <stdio.h>

void print_string(const char instring[]);

int main(void)
{
    print_string("Hello World");
    return 0;
}

void print_string(const char *instring)
{
        while(*instring!='\0')
    {
        printf("%c\n",*instring++);
    }
    return;
}

This will return each letter like so

H
e
l
l
o

W
o
r
l
d

But not in the desired arrangement. I have thought about implementing a do while loop to ignore spaces but as for printing duplicate letters on the same line I'm stumped. Also if you're wondering why I'm using pointers, a previous part of our homework was to print the length of a string using pointer arithmetic. Not sure if reworking it without pointers would be easier.

Upvotes: 0

Views: 1219

Answers (2)

4386427
4386427

Reputation: 44368

You can have a pointer to the previous character and use that to find out when to print a newline. Besides you need to check for spaces before printing current char. Like:

#include <stdio.h>

void print_string(const char instring[]);

int main(void)
{
    print_string("Hello World");
    return 0;
}

void print_string(const char *instring)
{
    const char *p = NULL;
    while(*instring!='\0')
    {
        if (p != NULL && *instring != *p && *instring != ' ') printf("\n");
        if (*instring != ' ') printf("%c",*instring);
        p = instring++;
    }
    printf("\n");
    return;
}

Output:

H
e
ll
o
W
o
r
l
d

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

Inside your loop while(*instring!='\0') you must have another loop that checks the characters following the current character. You must also skip the characte if it is white space. For example:

    while(*instring!='\0') {
        if (isspace(*instring)) {
            instring++;
        } else {
            printf("%c",*instring);
            int i= 1;
            while (*instring == *(instring+i)) {
                printf("%c",*(instring+i));
                i++;
            }
            printf("\n");
            instring += i;
        }
    }

Upvotes: 1

Related Questions