C语言基本函数运用示例:strlen、strcpy、strcat、strcmp、atoi
C语言基本函数运用示例:strlen、strcpy、strcat、strcmp、atoi
本文将介绍几个常用的C语言字符串处理函数,并提供相应的代码示例,帮助您更好地理解和运用这些函数。
1. strlen函数
strlen 函数用于计算字符串的长度,不包括字符串末尾的空字符('�')。
#include <stdio.h>
#include <string.h>
int main() {
char str[20];
printf('请输入一个字符串:');
scanf('%s', str);
int len = strlen(str);
printf('该字符串的长度为:%d
', len);
return 0;
}
2. strcpy函数
strcpy 函数用于将一个字符串复制到另一个字符串中。
#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20];
printf('请输入一个字符串:');
scanf('%s', str1);
strcpy(str2, str1);
printf('复制后的字符串为:%s
', str2);
return 0;
}
3. strcat函数
strcat 函数用于将一个字符串追加到另一个字符串的末尾。
#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20];
printf('请输入第一个字符串:');
scanf('%s', str1);
printf('请输入第二个字符串:');
scanf('%s', str2);
strcat(str1, str2);
printf('拼接后的字符串为:%s
', str1);
return 0;
}
4. strcmp函数
strcmp 函数用于比较两个字符串。如果两个字符串相等,则返回 0;如果第一个字符串小于第二个字符串,则返回负值;如果第一个字符串大于第二个字符串,则返回正值。
#include <stdio.h>
#include <string.h>
int main() {
char str1[20], str2[20];
printf('请输入第一个字符串:');
scanf('%s', str1);
printf('请输入第二个字符串:');
scanf('%s', str2);
int result = strcmp(str1, str2);
if (result == 0) {
printf('两个字符串相同
');
} else {
printf('两个字符串不同
');
}
return 0;
}
5. atoi函数
atoi 函数用于将字符串转换为整数。
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[20];
printf('请输入一个整数字符串:');
scanf('%s', str);
int num = atoi(str);
printf('转换后的整数为:%d
', num);
return 0;
}
通过学习这些函数的应用,您可以更有效地进行字符串处理,并编写更加高效的C语言程序。
原文地址: https://www.cveoy.top/t/topic/nQ1k 著作权归作者所有。请勿转载和采集!