字符串

来源:互联网 发布:淘宝注销了能再申请吗 编辑:程序博客网 时间:2024/06/05 10:35

在 C 语言中,字符串实际上是使用 null 字符 ‘\0’ 终止的一维字符数组。EX:char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};


1、fgets()的使用

////  main.c//  C_Practice////  Created by ztaotao on 2017/9/4.//  Copyright © 2017年 utotao. All rights reserved.//#include <stdio.h>#include <stdlib.h>//写一个返回传入字符串长度的函数int GetStrLength(char[]);int GetStrLength(char str[]){    int count = 0;    while (str[count] != '\0') {        count++;    }    return count;}int main(){    //char name1[] = {'j','a','c','k','\0'};    //定义字符串的几种方式    //字符串和字符数组的区别:最后一位是否是空字符    //char name1[] = {'j','a','c','k','\0'};    char name2[50] = "jack";    printf("请输入新名称:");    fgets(name2,10,stdin);   //从标准输入流中读取10个字节到数组name2中    //puts(name2);    for (int i = 0; i < 10; i++) {        printf("names2中第%d个元素是:%c\n",i + 1,name2[i]);    }   // printf("%s\n",name2);    int len = GetStrLength(name2);    printf("字符串的长度是:%d\n",len);    return 0;}

2、C 中有大量操作字符串的函数:

这里写图片描述


3、封装fgets

//封装fgets,用来接收字符串的字符数组,接收的字符总数int GetString(char [],int count);void GetString(char str[],int count){    //使用fgets函数接受字符串,使用\0替换字符数组的最后一位\n    fgets(str, count,stdin);    //返回\n字符所在的指针    char * find = strcha(str,'\n');    if(find)//如果找到了        *find = '\0';//根据找到的指针,修改指向的元素为\0}

4、注意

  1. gets函数不对接受字符串的buffer进行边界检测,会造成越界,从而产生bug
  2. 可以使用fgets(words1,20,stdin);代替gets,20表示最多读20-1个字符
  3. fgets会自动给最后一个元素设置为\n
原创粉丝点击