What is the usage of the string functions in the C language?

In C language, the string functions are used for manipulating and handling strings. Here are some common string functions and their uses:

  1. strlen(str): Returns the length of the string (excluding the ending null character ‘\0’).
    Example: int len = strlen(“hello”); // len has a value of 5.
  2. Copy the string from src to dest and return dest.
    Example: char dest[20];
    strcpy(dest, “hello”); // dest now contains “hello”
  3. The function strcat(dest, src) appends the string src to the end of the string dest and returns dest.

    Example:
    char dest[20] = “hello”;
    strcat(dest, ” world”); // value of dest is now “hello world”

  4. strcmp(str1, str2): compares the sizes of strings str1 and str2, returns 0 if they are equal, a positive number if str1 is greater than str2, and a negative number if str1 is less than str2.
    Example: int result = strcmp(“abc”, “def”); // the value of result is a negative number.
  5. The strchr function searches for the first occurrence of character ‘ch’ in the string ‘str’ and returns a pointer to that position. If not found, it returns NULL.
    Example: char* ptr = strchr(“hello”, ‘l’); // ptr points to the character ‘l’.
  6. The function strstr(str1, str2) searches for the first occurrence of the string str2 within the string str1, and then returns a pointer to that position. If the string is not found, it returns NULL.
    Example: char* ptr = strstr(“hello world”, “world”); // ptr points to “world”
  7. strtok(str, delimiters): splits the str string using the delimiters and returns a pointer to the first token. Multiple calls are needed to retrieve all tokens.
    Example: char str[20] = “hello world”;
    char* token = strtok(str, ” “); // token points to “hello”
    token = strtok(NULL, ” “); // token points to “world”

These are common usage of string functions that can help us easily handle and manipulate strings.

bannerAds