一、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-hant/n/371763.html