Common string operations, list these first.
#include<stdio.h> #include<string.h> #include<ctype.h> // delete the specified character from the string char * DeleteChar(char *s, char c)//c is the character to be deleted { int i, j = 0; for ( i = 0; *(s + i) != '\0'; i++) { if (*(s + i) != c) { *(s + j) = *(s + i); j++; } } *(s + j) = '\0'; return s; } // find the length of the string int str_length(const char *s) { int count = 0; while (*s++ != '\0') { count++; } return count; } // string case conversion void Tolower(char *s) { for (int i = 0; *(s + i) != '\0'; i++) { if (*(s + i) >= 65 && *(s + i) <= 90) { *(s + i) = *(s + i) + 32; } } } //string concatenation char * str_cat(char *s1, const char *s2) { char *temp = s1; while (*s1 != '\0') { s1 ++; }; while (*s2 != '\0') { * s1 ++ = * s2 ++; } * s1 = '\ 0'; return temp; } // string copy char * str_cpy(char *s1, char *s2) { char *temp = s1; while (*s2 != '\0') { * s1 ++ = * s2 ++; } * s1 = '\ 0'; return temp; } int main(void) { char s[20] = "hefahifAZfpiwf"; //string length printf("The length of the string is %d\n", str_length(s)); //remove the 'h' character from the string DeleteChar(s, 'h'); printf("%s\n", s); //Convert to lowercase characters Tolower(s); printf("Convert to lowercase: %s\n", s); // concatenate two characters char s1[30] = "haha"; char s2[10] = "ffafhi"; str_cat(s1, s2); printf("After connecting s2 to s1: %s\n", s1); char s3[10] = "zhaf"; char s4[10] = "fah"; str_cpy (s3, s4); printf("After copying s4 to s3: %s\n", s3); }
C language comes with string processing functions
1.strlen, find the length of the string
size_t strlen(const char *s) { size_t len = 0; while (*s++) len ++; return len; }
String length excluding null characters
2.strcpy, string copy
char *strcpy(char *s1, const char *s2) { char *temp = s1; while (*s1++ = *s2++); return temp; }