[英]Cutting a string?
int i;
char str[100];
char *p;
puts("Enter a string:");
gets(str);
system("cls");
p = &str;
for (i = 0; i < strlen(str); i++) {
printf("\n%s", p);
++p;
//printf("\n%d %d", i, *p);
}
for (i=2*i+1; i > strlen(str); i--) {
printf("%s\n", p);
p--;
//printf("\n%d %d", i, *p);
}
这个程序的输出是
"alpine
lpine
pine
ine
ne
e
e
ne
ine
pine
lpine
alpine".
如何让它只显示 'e' 一次,而不是两次?
与您的代码的问题是,当你p
在字符串的最后一个字符到达你增加它开始递减前一个更多的时间。 因此,如果您仔细查看第一个e
,还会打印空字符串。
尝试这个。
#include<stdio.h>
#include<string.h>
int main() {
int i;
char str[100];
char *p;
puts("Enter a string:");
gets(str);
p = &str;
for (i = 0; i < strlen(str); i++) {
printf("\n%s", p);
++p;
}
p--;
for (; i > 1; i--) {
p--;
printf("\n%s", p);
}
}
#include<stdio.h>
int main()
{
int i;
char str[100];
char *p;
puts("Enter a string:");
gets(str); // input word alpine, has six letters
system("cls");
p = &str;
for (i = 0; i < strlen(str); i++) {
printf("\n%s", p);
++p;
} // At the end of this i equals 6
// p is now pointing at a l p i n e \0
// ^ here at the null terminator
// In the following loop you set i to 13, this will loop 7 times.
// First you print the null terminator \0 and \n
// Then the 6 characters of alpine backwards
for (i = 2 * i + 1; i > strlen(str); i--)
{
printf("%s\n", p);
p--;
}
}
我会留给你找出解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.