C语言字符串函数

注意!!!要严格区分单引号和双引号!单引号内只能是一个字符,而双引号是字符数组
#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char mystr[]="猴子和我一起来,我和猴子一样帅"; gets(mystr); system("pause"); return EXIT_SUCCESS; }

puts()-----输出字符串并换行

gets()-----获取字符串,可以有空格

scanf-----获取输入,由于gets()和scanf()无法获知数组的大小,只有遇到结束符或换行符才终止,不可以有空格,因此可能导致数组越界,所以要加上宏 #define _CRT_SECURE_NO_WARNINGS

要么添加在代码的开头,要么添加在IDE的设置项中,如下

 

fgets() 三个参数 字符指针变量名  长度 输入流(std):两种情况----输入信息小于等于字符指针长度,会在输入的末尾加上 ,或者,在超过长度时,等待换行符 (也就是当我们敲击键盘回车键的时候)的输入,把 替换为;由此看出fgets()比gets()安全

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char cpc[10] = { 0 };
    char cj[10] = { 0 };
    printf("%p
",cpc);
    printf("%p
", cj);
    fgets(cpc, sizeof(cpc), stdin);
    printf("%s
", cpc);
    system("pause");
}

scanf("%*d%s")%*d忽略数字,*c忽略字符,如果忽略的是字符串就麻烦了,要写字符串指针长度个*c(例如有100就写100个)

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

int main()
{
    char wenwa[]="cpc";
    printf("%-5s",wenwa);
 printf("%5s",wenwa);
system("pause");
return EXIT_SUCCESS;
}

 strlen()字符串长度

int main()
{
   char wenwa[]="sunshine is lady rock you like a baby";
   int mylen = strlen(wenwa);
   printf("%d
",mylen);
   printf("%d
",sizeof(wenwa));    
   system("pause");  
   return EXIT_SUCCESS;   
}

strcpy(目标地址,源地址)字符串拷贝

char target[];
char src[];
if (strcpy(target,src)!=NULL)
{
     
}

strncpy()

int main()
{
     char mywords[]="喜欢陈培昌";
     char hiswords[];
     strcnpy(hiswords,mywords);
     hiswords[5]=0;
     printf(hiswords);
     return EXIT_SUCCESS;  
}

 strcat()

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

int main()
{
   char myarr[] ={0};
   char myarr2[]={0};
   gets(myarr);
   gets(myarr2);
   printf(strcat(myarr,myarr2));
   system("pause");
   return EXIT_SUCCESS;  
}

strncat()

int main()
{
    
    char myarr[8] = { 0 };
    char myarr2[10]={ 0 };
    gets(myarr);
    gets(myarr2);
    strncat(myarr, myarr2, sizeof(myarr)-strlen(myarr) - 1);
    puts(myarr);
    system("pause");
    return EXIT_SUCCESS;
}

sprintf()向数组打印字符串

strchr(a,'c')在a中找到‘c’,并返回位置。

char *c = strchr(a,'c')

strstr (a,"345")---查找字符串,找不到,返回NULL

strtok() 分割字符串

char *p = strtok();

printf(p)

atoi()

char wenwa[] ="789";
printf(atoi(wenwa));

wenwa是char数组
atoi()把数组转换为整数,两者地址不一样

一种怪异的把字符串转换为数字的方法

char mynum[] = "456";

(mynum[0]-0x30)*1000;
+
(mynum[1]-0x30)*100;
+
(mynum[2]-0x30)*10;

 字符串逆置

 查找数组中第二大的数字

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

int main()
{
   int mynum[]={43,88,56,24,78,12,8}; 
   return EXIT_SUCCESS;
}

 strlen字符串长度不包括末尾的'/0'

sizeof()返回的是数组一共占据了多少字节的内存空间

sprintf存在缓冲区溢出的问题。

strtok()字符串拆分

原文地址:https://www.cnblogs.com/saintdingspage/p/10332395.html