[C语言]C语言中给的字符数组清零操作方法

前言:

    C语言不能对这个数组赋值,只能通过遍历数组达到给数组中每个元素赋值的目的。初始化的时候可以用inta[4]={0};这样给整个数组元素赋值为0,若想给已初始化的数组清零,也只能遍历数组。

    在C语言中,所谓的“清空”,意思是“无视里面的数据”,而不是“让里面没有数据”。有时候可能需要把一个数组清零,意思是全部数据都用0填充,可以用库函数来实现。假设数组名为a,无论什么类型也无论几维都一样,可以写成memset(a,0,sizeof(a));

法1:通过遍历的方式

#include<stdio.h>
#include<string.h>
int main()
{
  char a[10];
  printf("请输入你的英文名字:");
  scanf("%s",a);
  for(int i=0;i<10;i++) 
  {
    a[i]=0xff;  //或者换成a[i]=0; 结果一样
  }
  printf("%s\n",a);
}

法2:利用memset函数

    void *memset(void *s, int ch, size_t n);

    函数解释:将s中当前位置后面的n个字节 (typedef unsigned int size_t )用 ch 替换并返回 s 。memset:在一段内存块中填充某个给定的值,它是对较大的结构体数组进行清零操作的一种最快方法,加一个#include<string.h>的预处理命令,然后使用memset()函数进行处理。具体到你提的问题的操作就是,在加了头文件后程序中写memset(a,0,sizeof(a));即可实现数组清零的功能。

#include<stdio.h>
#include<string.h>
int main()
{
    char a[10];
    printf("请输入你的英文名字:");
    scanf("%s",a);
    memset(a,0,sizeof(a));
    printf("%s\n",a);
}

 两种方法效果都是一样的。

  • 16
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用两层循环,第一层循环遍历输入的每一行字符串,第二层循环遍历当前行字符串的每一个字符,然后使用if-else语句进行分类统计。 具体代码如下: ```c #include <stdio.h> #include <string.h> int main() { char arr[100][100]; int n, letter_count, digit_count, space_count, other_count; printf("Enter the number of lines: "); scanf("%d", &n); getchar(); // 吃掉输入数字后的回车符 for (int i = 0; i < n; i++) { printf("Enter string %d: ", i+1); gets(arr[i]); // 获取当前行字符串 } for (int i = 0; i < n; i++) { letter_count = digit_count = space_count = other_count = 0; // 每次循环前先清零 for (int j = 0; j < strlen(arr[i]); j++) { if (arr[i][j] >= 'a' && arr[i][j] <= 'z' || arr[i][j] >= 'A' && arr[i][j] <= 'Z') { letter_count++; } else if (arr[i][j] >= '0' && arr[i][j] <= '9') { digit_count++; } else if (arr[i][j] == ' ') { space_count++; } else { other_count++; } } printf("Line %d:\n", i+1); printf("Letter count: %d\n", letter_count); printf("Digit count: %d\n", digit_count); printf("Space count: %d\n", space_count); printf("Other count: %d\n", other_count); } return 0; } ``` 示例输入: ``` Enter the number of lines: 3 Enter string 1: Hello World! Enter string 2: 12345 abcdefg Enter string 3: ^&$#) ``` 输出结果: ``` Line 1: Letter count: 10 Digit count: 0 Space count: 1 Other count: 1 Line 2: Letter count: 7 Digit count: 5 Space count: 1 Other count: 0 Line 3: Letter count: 0 Digit count: 0 Space count: 0 Other count: 6 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值