一、strcpy函數
strcpy函數是C語言中常用的字元串拷貝函數,其原型為:
char *strcpy(char *dest, const char *src);
該函數的作用是將源字元串(src)拷貝到目標字元串(dest)中,如果目標字元串(dest)中原有值,則原有值會被覆蓋。使用該函數時,需保證目標字元串(dest)空間足夠大,可用strlen函數計算源字元串(src)長度,如:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s1[100] = "Hello, World!";
char s2[100];
strcpy(s2, s1);
printf("%s", s2);
return 0;
}
該代碼會輸出:Hello, World!
二、strcat函數
strcat函數是C語言中常用的字元串連接函數,其原型為:
char *strcat(char *dest, const char *src);
該函數的作用是將源字元串(src)連接到目標字元串(dest)的末尾。使用該函數時,需保證目標字元串(dest)空間足夠大,可用strlen函數計算源字元串(src)長度,如:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s1[100] = "Hello, ";
char s2[100] = "World!";
strcat(s1, s2);
printf("%s", s1);
return 0;
}
該代碼會輸出:Hello, World!
三、strcmp函數
strcmp函數是C語言中常用的字元串比較函數,其原型為:
int strcmp(const char *s1, const char *s2);
該函數的作用是將字元串s1與s2進行比較,如果s1大於s2,則返回正數,如果s1等於s2,則返回0,如果s1小於s2,則返回負數,如:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s1[100] = "Hello";
char s2[100] = "World";
int result = strcmp(s1, s2);
if (result > 0)
{
printf("%s is greater than %s", s1, s2);
}
else if (result == 0)
{
printf("%s is equal to %s", s1, s2);
}
else
{
printf("%s is less than %s", s1, s2);
}
return 0;
}
該代碼會輸出:Hello is less than World
四、strlen函數
strlen函數是C語言中常用的字元串長度函數,其原型為:
size_t strlen(const char *s);
該函數的作用是計算字元串s的長度(不包括字元串結束符「\0」),如:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s[100] = "Hello, World!";
size_t len = strlen(s);
printf("%zu", len);
return 0;
}
該代碼會輸出:13
五、strstr函數
strstr函數是C語言中常用的字元串查找函數,其原型為:
char *strstr(const char *haystack, const char *needle);
該函數的作用是在字元串haystack中查找字元串needle第一次出現的位置,如果找到,則返回第一次出現的位置指針,如果未找到,則返回NULL,如:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s1[100] = "Hello, World!";
char s2[100] = "World";
char *result = strstr(s1, s2);
if (result != NULL)
{
printf("%s", result);
}
else
{
printf("Not found");
}
return 0;
}
該代碼會輸出:World!
原創文章,作者:MNRRT,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371763.html
微信掃一掃
支付寶掃一掃