文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
有时候我们需要截断输出字符串,比如只输出前面某几个字符或者后面某几个字符,这就是我今天要说的。
在说方法之前我们需要了解一下puts函数:
Writes the C string pointed by str to stdout and appends a newline character ('\n').
The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This final null-character is not copied to stdout.
下面介绍方法。
只输出前面某几个字符:
#include <stdio.h>
int main(){
int m,n,i,len;
char s[20]="www.slyar.com";
s[9]=0;
puts(s);
return 0;
}
运行后可以看到,输出了前8个字符,第9个以后的字符被截断了。关键句 s[9]=0; 本来应该是s[9]='\0',但s是字符串型,所以当把0赋给s[9]的时候,程序会把0的ascii码赋给s[9],也就是NUL(空),所以字符串被截断。
只输出后面某几个字符:
#include <stdio.h>
int main(){
int m,n,i,len;
char s[20]="www.slyar.com";
puts(s+4);
return 0;
}
运行后可以看到,输出了后10个字符,而前4个字符被截断了。关键句puts(s+4),我们知道字符数组的名字就是这个数组的内存首地址,所以s+4相当于首地址向后移动了4位,所以程序会忽略前4位字符而从第5位开始输出。
转载请注明:Slyar Home » 使用puts()截断输出字符串