Making a pyramid in C

2019-09-21 09:41发布

问题:

I have to make a pyramid only using C, no C++. what I have to do is this, I have a string "this is a string " (yes the space is suppose to be there), and I have to "remove" one letter from both sides, and print that. like this

"this is a string "
 "his is a string"
  "is a strin"
   "s a stri"
    " a str"

This is repeated until there are no more characters. My teacher says to use substrings, is there any thing in C that says

print from location (index 0 to index x)
print from location (index 1 to index x-1)

I know I have to use a for loop.

回答1:

This is homework, so I'll just get you started.

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

int main(void) {
    char src[] = "this is a test string";
    char dest[5] = {0}; // 4 chars + terminator
    for (int i = 0; i * 4 < strlen(src); i++) {
        strncpy(dest, src+(i*4), 4);
        puts(dest);
    }
}

Output:

this
 is 
a te
st s
trin
g

So for your pyramid problem, you will want to take the substring of the your original string. Set the beginning of your substring one character ahead of your original string, and strlen(original) - 1 for the end character. Then loop that process.



回答2:

Yes, there is a printing facility enabling you to print substrings. Read the spec for printf.

There is a way to give it a parameter (int) which limits how many characters from another parameter (char*) it prints.



回答3:

To chop off the first character of a string, simply treat the next character as the start of the string. So, instead of puts(str), call puts(str + 1).

To chop off the last character of a string, overwrite the last character with a \0 character. Since this is a destructive operation, it is probably a good idea to operate a copy of the original string.

To solve this problem, then, make a copy of the string. Keep two pointers: one at the front of the copied string walking towards the end, and one at the end walking towards the front.