#include <stdio.h>
#define LENGTH 128
#define NUMBER 5

int&nbsp;main(void){
int&nbsp;i;
char&nbsp;s[NUMBER][LENGTH];

for(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;NUMBER;&nbsp;i++){
printf(&quot;s[%d]&nbsp;:&nbsp;&quot;,&nbsp;i);
scanf(&quot;%s&quot;,&nbsp;s[i]);
}

puts(&quot;-----------打印字符串-----------&quot;);

for(i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;NUMBER;&nbsp;i++){
printf(&quot;s[%d]&nbsp;=&nbsp;\&quot;%s\&quot;\n&quot;,&nbsp;i,&nbsp;s[i]);
}

return&nbsp;0;
}

程序中的数组s是5行128列的二维数组,即每行的字符串长度为127(null字符占用1节存储空间),可存储5行字符串。
注:字符串数据,将它们传入scanf函数时不可以带 & 运算符。

运行结果:
C语言 读取字符串数组中的字符串并获取字符串的长度_字符串


#include <stdio.h>
#define LENGTH 128

int&nbsp;str_length(const&nbsp;char&nbsp;s[]){
int&nbsp;len&nbsp;=&nbsp;0;

while&nbsp;(s[len]){
len++;
}
return&nbsp;len;&nbsp;&nbsp;// 返回数组str中首个值为null的元素的下标值
}

int&nbsp;main(void){
char&nbsp;str[LENGTH];

printf(&quot;请输入字符串:&quot;);
scanf(&quot;%s&quot;,&nbsp;str);

printf(&quot;字符串\&quot;%s\&quot;的长度是&nbsp;%d。&nbsp;\n&quot;,&nbsp;str,&nbsp;str_length(str));
}

运行结果:
C语言 读取字符串数组中的字符串并获取字符串的长度_字符串_02
while 语句在循环条件表达式为非0的情况下,会执行循环体语句。该循环语句,会从头开始遍历数组。
循环继续的条件是, s[len]不是0,即不是null字符。变量len的初始值为0,每次执行循环体语句就自增1,直至出现null字符为止。

数组的长度为128,实际存储的长度只有5,剩下的都是空的。由此可知,字符串不一定正好撑满字符串数组。因为字符串中含有表示其末尾的null字符,所以第一个字符到 ‘\0’ (的前一个字符)为止的字符数,就是该字符串的长度。

使用指针遍历,获取字符串长度
#include <stdio.h>

int&nbsp;str_length&nbsp;(const&nbsp;char&nbsp;*s){
int&nbsp;len&nbsp;=&nbsp;0;

while&nbsp;(*s++){
len++;
}

return&nbsp;len;
}

int&nbsp;main(void){
char&nbsp;str[128];

printf(&quot;请输入字符串:&quot;);
scanf(&quot;%s&quot;,&nbsp;str);

printf(&quot;字符串\&quot;%s\&quot;的长度是%d。\n&quot;,&nbsp;str,&nbsp;str_length(str));

return&nbsp;0;
}
使用库中的函数获取字符串的长度

头文件

原形

说明

返回值

#include <string.h>

size_t strlen(const char *s)

求出s指向的字符串的长度(不包括null字符)。

返回s指向的字符串的长度。

#include <stdio.h>
#include <string.h>

int&nbsp;main(void){
char&nbsp;*p&nbsp;=&nbsp;&quot;vvcat&quot;;

printf(&quot;字符串的长度为%d&quot;,&nbsp;strlen(p));

return&nbsp;0;
}
实现strlen函数
#include <stdio.h>

size_t&nbsp;strlen(const&nbsp;char&nbsp;*s){
size_t&nbsp;len&nbsp;=&nbsp;0;

while(*s++){
len++;
}

return&nbsp;len;
}&nbsp;

int&nbsp;main(void){
char&nbsp;*p&nbsp;=&nbsp;&quot;vvcat&quot;;

printf(&quot;字符串的长度为%d&quot;,&nbsp;strlen(p));

return&nbsp;0;
}