字符串相关(字符串数组,字符串处理相关函数、自实现函数)

    xiaoxiao2021-03-25  67

    // main.c // 字符串相关(字符串数组,字符串处理相关函数) // // Created by fzl // Copyright © fzl. All rights reserved. // #include <stdio.h> #include <string.h> /*指针数组*/ void test1() { //字符串数组 char string1[2][10]={"123","456"}; //先算[],指针数组,每一个变量都是指针 char *arr[3]={"123","456","678"}; printf("%s\n",arr[0]); } /*strlen()函数和sizeof运算符的区别*/ void test2() { /** * strlen()计算字符串实际字符长度,不包括'\0' */ /** * sizeof()是计算变量所占字节大小 */ char string[10]="123456"; int length=strlen(string); char *p="hello"; printf("%lu\n",sizeof(p)); printf("%lu\n",strlen(p)); printf("%d\n",length); } /*strcpy()字符串拷贝函数*/ void test3() { char str1[10]="12233"; char str2[10]="4565768"; strcpy(str2, str1); printf("str2=%s\n",str2); /* 不可以,试图改变文字常量的内容 char *p="123"; strcpy(p,"2345"); */ char str[10]; strcpy(str, "1234"); printf("str=%s\n",str); } /* strcat()字符串连接函数*/ void test4() { char str[10]="world"; char str1[20]="hello"; strcat(str1, str); printf("str1=%s\nstr=%s\n",str1,str); } /* strcmp()字符串比较函数*/ void test5() { char str[10]="abcd"; char str1[10]="ad"; int a=strcmp(str, str1); printf("%d\n",a); } /* strncpy()*/ void test6() { char str[10]="123"; char str1[10]="456hello"; strncpy(str1, str, 3); printf("str1=%s\n",str1); } /*strncat()*/ void test7() { char str[10]="123"; char str1[10]="456"; strncat(str1, str, 1); printf("str1=%s\n",str1); } /*strncmp()*/ void test8() { char str[10]="123"; char str1[10]="12"; int a=strncmp(str,str1,2); printf("a=%d\n",a); } /**自定义strlen函数*/ int myStrlen(const char *string) { int i=0; for (; *string!='\0'; i++) { string++; } return i; } /**自定义strcpy()*/ void myStrcpy(char *dest,const char *source) { int i=0; for (; *source!=0; i++) { *dest=*source; dest++; source++; } *dest='\0'; } int main() { char str[10]="124423"; char str1[10]; myStrcpy(str1,str); printf("str1=%s\n",str1); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-32819.html

    最新回复(0)