C 语言中 str 的用法
简介:
str 是 C 语言中最常用的字符串处理函数之一。它允许操作以 null 结尾的字符数组(字符串)并执行各种操作。
语法:
<code class="c">char *str(const char *str1, const char *str2);</code>
参数:
立即学习“C语言免费学习笔记(深入)”;
str1:要执行操作的第一个字符串。 str2:要执行操作的第二个字符串。返回值:
返回一个指向结果字符串的指针。
用法:
str 函数可以用于各种字符串操作,包括:
示例:
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
// 字符串连接
strcat(str1, " ");
strcat(str1, str2);
printf("连接后的字符串:%s\n", str1);
// 字符串比较
int result = strcmp(str1, "Hello World");
if (result == 0) {
printf("字符串相等\n");
} else if (result > 0) {
printf("str1 大于 str2\n");
} else {
printf("str1 小于 str2\n");
}
// 字符串复制
strcpy(str1, str2);
printf("复制后的字符串:%s\n", str1);
// 字符串长度
int length = strlen(str1);
printf("字符串长度:%d\n", length);
return 0;
}</code>输出:
<code>连接后的字符串:Hello World 字符串相等 复制后的字符串:World 字符串长度:5</code>
