C和指针第九章的四个小代码

本文介绍了几个实用的C语言字符串操作技巧,包括自定义货币格式输出、统计特定单词出现次数及字符串复制等,有助于提高编程效率。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//作用是将那个数字按照一定格式输出9_14_15
void dollars( char *dest,char const *src );

int main()
{
    char a[100];
    char b[300];
    printf("请输入数字\n");
    gets(a);
    dollars( b, a);
    puts(b);
    //printf("Hello world!\n");
    return 0;
}
void dollars( char *dest,char const *src )
{
    int length, i;
    if( dest == NULL || src == NULL )
    {
        return;
    }
    *dest++ = '$';
    length = strlen(src);
    if( length >= 3 )
    {
        for(i = length-2; i>0; )
        {
            *dest++ = *src++;
            if(--i > 0 && i % 3 ==0 )
                *dest++ = ',';
        }
    }
    else
    {
        *dest ++= '0';
    }
    *dest++ = '.';
    *dest++ = length < 2 ? '0':*src++;
    *dest++ = length < 1 ? '0':*src;
    *dest ='\0';
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//单词以空白字符分开,并且计算the出现的数目9_14_11
int main()
{
    char a[100];
    char *word;
    char const whitespace[] = " \n\r\f\t\v ";
    printf("输入一大句英文!\n");
    gets(a);
    int count = 0;
    for( word = strtok( a, whitespace ); word != NULL; word = strtok( NULL, whitespace) )
    {
        if( strcmp( word, "the" ) == 0 )
            count+=1;
    }
    printf( "%d\n", count );

    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

//类似strcpy的一个函数,但是返回的是指向目标字符串末尾的指针
char *mystrcpy(char const *dest, char const *src);

int main()
{
    char a[10]="ABC";
    char b[7]="CDefg";
    // char *first;
    //char *last;
    //first = strcpy(a, b);
    //puts(a);
    mystrcpy(a, b);
    /*int j;
    j = strlen (a);
    int i;
    for(i=0; i < j; i++)
    {
        printf("%c",a[i]);
    }*/
    puts(a);
    return 0;
}
char * mystrcpy(char const *dest, char const *src)
{
    char *m,*n;
    m = dest;
    n = src;
    char *p;
    while(( *m++ = *n++ )!='\0')
    ;
    p=(m-1);
    return p;
}
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
//计算字符串的长度,也可以接受由于strnxx函数导致的没有'\0'的字符串长度,实际上就是看一个数组里有'\0'就计算那个长,否则就是数组长度
int mystrlen( char const *string, int size );

int main()
{
    char a[7]="ABC";
    char b[5]="CDEFG";
    strncpy(a, b, 5);
    int count;
    count = mystrlen(a, 8);
    printf("%d\n", count);
    return 0;
}
int mystrlen( char const *string, int size )
{
    int length = 0;
    for(length = 0; length < size; length++)
    {
        if(*string++ == '\0')
            break;
    }
    return length;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值