php函数源代码 C编写 【持续更新】

 由于经常被抓取文章内容,在此附上博客文章网址:,偶尔会更新某些出错的数据或文字,建议到我博客地址 :  --> 点击这里

strlen()

获取字符串长度,成功则返回字符串 string 的长度;如果 string 为空,则返回 0。

#include<stdio.h>
#include<stdlib.h>
#define N 1000
int count = 0;

int strlen(char *str)
{
    int num = 0;                    //定义一个计数器
    while('\0' != *str++)
    {
        num++;
    }
    return num;
}

void test(char *str)
{
    printf("所要测试的字符串为: %s\n",str);
    count = strlen(str);                            //调用函数
    printf("所输入的字符串长度为:%d\n\n",count);
}

void  main()
{
    char str1[] = "hello world!";    //这样的赋值方式会有在尾部自动一个'\0'
    char *str2 = "hello world!";        //这样的赋值方式会有在尾部自动一个'\0'
    char str3[20] = "world hello!";   //这样的赋值方式会在剩余的位置全部自动添加'\0'
    char str4[N] = {0};
    test(str1);
    test(str2);
    test(str3);

    printf("请输入所要测试的数组:\n");
    gets(str4);            //此函数会在最后添加NULL字符 即'\0'
    test(str4);
system(
"pause"); }

 

strcpy()

head.h

#include<stdio.h>
#include<string.h>
#define N 100
void strcpy1(char *str_cpy, char const *str);

_strcpy().c

#include"head.h"


void strcpy1(char *str_cpy,char const *str)  //为了保证主数组的只读性,所以加"const"修饰
{
    while(*str != '\0')
    {
        *str_cpy = *str ;
        str_cpy ++;
        str++;
    }
    *str_cpy = '\0';       //添加结束符
}

main.c

#include"head.h"

void main()
{
    char str[N];
    char str_cpy[N] ;
    printf("请输入所要主字符串数组:\n");
    scanf("%s",&str);

    strcpy1(str_cpy,str);      //复制
    printf("复制前的主字符串为的%s\n",str);
    printf("复制后新字符串为的%s\n",str_cpy);

    getchar();
    getchar();
}

 

explode()

#include<stdio.h>
#include<stdlib.h>

#define N 50
char *ptr[5] = {0};         //定义指针数组,用来保存分割后的子串
char temp[N] = {0};        //定义临时字符数组,用来临时保存分割后的子串

void explode(char *str,char c)      //char c 类型用来保存分隔符
{
    int i = 0;
    while((*str) != c)
    {
        temp[i] = *str;            //指针中的字符串赋值给临时数组temp
        str++;
        i++;    
    }
    str++;                        //此时 (*str) 是 分割符 c,自增1跳过分隔符
    temp[i] = '\0';            //将分割的子串添加结束符号 '\0'
    printf("%s\n",temp);   //将分割后的子串打印出来
    i = 0;                            //    将i置零,方便下次使用临时数    
while((*str) != '\0') { temp[i] = *str; //指针中的字符串赋值给临时数组temp str++; i++; } str++; //此时 (*str) 是 结束符,自增1跳过结束符 temp[i] = '\0'; //将分割的子串添加结束符号 '\0' printf("%s\n",temp); //将分割后的子串打印出来 i = 0; // 将i置零,方便下次使用临时数 return ; } void main() { char *str = "hello,world!"; char b[N] = {0} ; //用于保存用户所输入的数组 char c; //用于保存用户所输入的分割符 printf("下面用'hello,world!'作为示例,其中分割符为','\n"); printf("下面是使用分割函数explode(hello,world!,'c')的结果\n"); explode(str,','); //此函数不局限于 ',' 作为分隔符 ,可以用其他符号 printf("请输入只有两个子字符串的字符串:例如hello,world!\n"); scanf("%s",b); printf("请输入你想用的分隔符:\n"); getchar(); //缓冲点回车键,不然会以回车键作为分隔符,程序崩溃 scanf("%c",&c); explode(b,c); //此函数不局限于 ',' 作为分隔符 ,可以用其他符号 system("pause"); }

 

posted @ 2017-08-20 16:03  hongxinerke  阅读(635)  评论(0编辑  收藏  举报