sprintf函数,strchr函数,strlen函数

一: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;
}

上面的代码为一道题:竖式计算(乘法)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值