字符串与终止符
Coddy 面向 C# 开发者的 C 课程的第 14 课,共 48 课。
C# 字符串是不可变的托管 UTF-16 序列。C 字符串是以终止符结尾的字节缓冲区,并有单独的容量;strlen 统计字节数,并在遇到第一个零字节时停止。
C 字符串在零字节处结束。容量包括用于终止符的空间,而 strlen 统计前面的字节数。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Main(){
string s="cat";Console.WriteLine(s.Length);
}
}
C# 输出:
3C 示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
char s[]="cat";printf("%zu:%zu\n",strlen(s),sizeof s);
return 0;
}
C 输出:
3:4挑战
简单输入是一行 ASCII 字符串,长度小于 128 字节,也可能为空。返回去掉结尾的零字节和输入换行符后的字节长度。
编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查范围,否则所有数字任务数据都足够小,不会溢出。只打印指定的输出;显示驱动程序时,由驱动程序负责解析输入和输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){char text[128]="";if(fgets(text,sizeof text,stdin))text[strcspn(text,"\n")]=0;printf("%zu\n",text_length(text));return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 C中的所有课
自己练习: C 在线编译器