一:strlen函数
返回一个字符串的实际长度。
实际长度就是:结束标记‘\0’之前的字符个数。对于结束字符和未赋值的字符串空间是不算的。
二:sprintf函数
简单地说,sprintf可以把变量格式化的输入到一个字符数组。
一下面的例子为例:
#include<stdio.h>
#include<string.h>
int main()
{
char buf[99];
int abc = 775;
int de = 33;
int x = abc * (de % 10);//2325
int y = abc * (de / 10);//2325
int z = abc * de;//25575
sprintf(buf, "%d%d%d%d%d", abc, de, x, y, z); //这里
for ( int i = 0; i < strlen(buf); i++) //在这里 strlen(buf)为18
{
printf("%c ", buf[i]);
}
printf("\n");
}
输出:
7 7 5 3 3 2 3 2 5 2 3 2 5 2 5 5 7 5
值得注意的是:变量(abc, de, x, y, z)被拆分成了单个字符保存到数组字符数组中。
所以,使用sprintf函数时,字符数组要设置的大一些,以防空间不够。
三:strchr函数与strlen函数
此函数的作用为在一个字符串中查找单个字符,
若找到了:返回该字符第一次出现时的地址,
若没找到 :返回NULL。
#include <stdio.h>
#include <string.h>
int main()
{
int count = 0;
char s[20], buf[99];
scanf("%s", s); //s前不需要&符号
for (int abc = 100; abc <= 999; abc++)
{
for (int de = 10; de <= 99; de++)
{
int x = abc * (de % 10);
int y = abc * (de / 10);
int z = abc * de;
sprintf(buf, "%d%d%d%d%d", abc, de, x, y, z);
int ok = 1;
for (int i = 0; i < strlen(buf); i++)
{
if ( strchr(s, buf[i]) == NULL) //这里
ok = 0;
}
if (ok)
{
printf("<%d>\n", ++count);
printf("%5d\nX%4d\n-----\n%5d\n%4d\n-----\n%5d\n\n", abc, de, x, y, z);
}
}
}
printf("The number of sulotions = %d\n", count);
return 0;
}
上面的代码为一道题:竖式计算(乘法)