字符串


在 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值