C 语言中计算字符串长度和宽度的函数
在 C 语言中,计算字符串长度和宽度的函数分别为:
strlen() 函数:用于计算字符串的长度,返回字符串中字符的数量(不包括终止符 '\0')。 strwidth() 函数:用于计算字符串在终端中的宽度,返回字符串中显示像素的数量。使用方法
strlen() 函数:
立即学习“C语言免费学习笔记(深入)”;
语法:
size_t strlen(const char *str);
参数:
const char *str:要计算长度的字符串。
strwidth() 函数:
语法:
int strwidth(const char *str);
参数:
const char *str:要计算宽度的字符串。
示例
计算字符串长度:
<code class="c">#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
printf("字符串 \"%s\" 的长度为:%d\n", str, len);
return EXIT_SUCCESS;
}</code>输出:
<code>字符串 "Hello, world!" 的长度为:13</code>
计算字符串宽度:
<code class="c">#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
int main() {
char str[] = "Hello, world!";
int width = strwidth(str);
printf("字符串 \"%s\" 的宽度为:%d\n", str, width);
return EXIT_SUCCESS;
}</code>输出:
<code>字符串 "Hello, world!" 的宽度为:13</code>
