C语言没有字符串变量,它使用char
数组来存储字符串。
示例代码
#include <stdio.h>
int main()
{
char sample[] = "this is a test string?\n";
char *ps = sample;
while (*ps != '\0')
{
putchar(*ps);
ps++;
}
system("pause");
return(0);
}
执行上面示例代码,得到以下结果:
this is a test string?
消除冗余比较。参考以下示例代码:
#include <stdio.h>
int main()
{
char sample[] = "this is a test string?\n";
char *ps = sample;
while(*ps)
putchar(*ps++);
return(0);
}
执行上面示例代码,得到以下结果:
this is a test string?
消除while
循环中的语句,可将所有操作放在while
语句的评估中。putchar()
函数返回显示的字符。
#include <stdio.h>
int main()
{
char sample[] = "this is a test string?\n";
char *ps = sample;
while (putchar(*ps++))
;
system("pause");
return(0);
}
执行上面示例代码,得到以下结果:
this is a test string?