博客
关于我
C语言 字符串
阅读量:797 次
发布时间:2023-04-03

本文共 1237 字,大约阅读时间需要 4 分钟。

C语言字符串处理基础

1. 关于字符串打印终止符

在C语言中,printf函数会遇到\0终止符时停止打印。"\0"代表ASCII中的空字符(编号0)。需要注意的是,未初始化的数组元素默认值为0,因此如果不明确赋值,字符串末尾可能会有\0

例如:

char arr[10] = {'h', 'e', 'l', 'l', 'o'};// 这里只赋了5个字符,后面5个元素默认为0

而:

char arr2[] = "hello";// 这里会自动在末尾添加一个`\0`,字符串长度为6

2. 数组字符串赋值注意事项

  • 初始化数组时可以直接赋值,但如果在声明后重新赋值,需要使用strcpy函数(通常用于结构体中包含字符串的情况)。
  • 不能直接使用= "字符串"赋值数组,除非使用strcpy

例如:

char arr[10];strcpy(arr, "wang");

3. 字符串数组和字符串常量

  • 字符串常量 "字符串" 会自动终止于\0,而数组字符串则需要手动终止。
  • 例如:
char str3[5] = {'a', 'b', 'c'};// 后面没有`\0`,打印时会一直输出到数组末尾

4. 字符串长度计算

  • sizeof("字符串")会包含终止符\0,因此长度比字符串实际字符数多1。
  • 例如:
sizeof("hello world") = 12(包括`\0`)

5. 遍历字符串

  • 使用指针逐字符打印字符串。
  • 使用数组逐字符打印字符串。

例如:

char str[12] = "hello world";int i = 0;while (str[i]) {    putchar(str[i]);    i++;}

6. 字符串输入与输出

  • 使用scanf函数读取字符串到数组。
  • 使用printf函数输出字符串。

例如:

char str[10] = {0};scanf("%s", str);

7. 指针与字符串常量

  • 字符串常量地址不能修改。
  • 指针需要指向可读写内存地址才能修改。

例如:

char *p = str; // str是一个可读写的数组scanf("%s", p);

8. 字符串数组与指针数组

  • 字符串数组和指针数组在使用时需注意终止符。
  • 遍历时可以使用*pp[i]访问字符。

例如:

char *p = str;while (*p) {    putchar(*p);    p++;}

9. 字符串数组初始化

  • 可以通过手动赋值每个字符,或者直接赋值字符串常量(后者会自动添加\0)。

例如:

char str1[100] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};

10. 字符串数组输入

  • 使用scanf函数读取字符串到数组时,需确保数组大小足够。
  • 未初始化的数组元素默认为0,不会影响读取结果。

例如:

char str[10] = {0};scanf("%s", str);

转载地址:http://nwrfk.baihongyu.com/

你可能感兴趣的文章
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
ViewHolder的改进写法
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>