ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112String Library Functio…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 26 of 39
    Topic Study Note Illustration
    26

    String Functions, Library Functions

    In C programming, string manipulation is essential for handling text-based data. C doesn't have a built-in string data type but instead uses character arrays, which are arrays...

    String Functions and Library Functions in C

    In C programming, string manipulation is essential for handling text-based data. C doesn't have a built-in string data type but instead uses character arrays, which are arrays of char terminated with a null character '\0'. To help manage strings, C provides a range of string functions in the <string.h> library. These functions allow you to perform common operations like copying, concatenating, comparing, and searching strings.

    Let's explore the key string functions provided by the <string.h> library.


    1. strlen() - Length of a String

    The strlen() function returns the number of characters in a string, excluding the null-terminating character '\0'.

    Syntax:

    size_t strlen(const char *str);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        
        printf("Length of string: %zu\n", strlen(str));  // Output: 13
        
        return 0;
    }
    

    Explanation:

    • strlen(str) returns 13, which is the number of characters in the string "Hello, World!", excluding the null terminator.

    2. strcpy() - Copying Strings

    The strcpy() function copies the content of one string into another. The destination string must be large enough to hold the copied string and the null-terminator.

    Syntax:

    char *strcpy(char *dest, const char *src);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char src[] = "Hello";
        char dest[20];
        
        strcpy(dest, src);  // Copies "Hello" into dest
        
        printf("Destination string: %s\n", dest);  // Output: Hello
        
        return 0;
    }
    

    Explanation:

    • strcpy(dest, src) copies the string from src to dest, including the null-terminating character.

    3. strcat() - Concatenating Strings

    The strcat() function appends the source string to the destination string, starting from the null character '\0' in the destination string.

    Syntax:

    char *strcat(char *dest, const char *src);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[20] = "Hello";
        char str2[] = " World!";
        
        strcat(str1, str2);  // Concatenates " World!" to "Hello"
        
        printf("Concatenated string: %s\n", str1);  // Output: Hello World!
        
        return 0;
    }
    

    Explanation:

    • strcat(str1, str2) appends the content of str2 to str1 and the result is "Hello World!".

    4. strcmp() - Comparing Strings

    The strcmp() function compares two strings lexicographically (character by character).

    • It returns:
      • 0 if the strings are equal.
      • A negative value if the first string is lexicographically less than the second.
      • A positive value if the first string is lexicographically greater than the second.

    Syntax:

    int strcmp(const char *str1, const char *str2);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str1[] = "Apple";
        char str2[] = "Banana";
        
        int result = strcmp(str1, str2);
        
        if (result == 0) {
            printf("Strings are equal.\n");
        } else if (result < 0) {
            printf("'%s' is less than '%s'.\n", str1, str2);
        } else {
            printf("'%s' is greater than '%s'.\n", str1, str2);
        }
        
        return 0;
    }
    

    Explanation:

    • strcmp(str1, str2) compares "Apple" and "Banana", and since "Apple" is lexicographically less than "Banana", it returns a negative value.

    Output:

    'Apple' is less than 'Banana'.
    

    5. strchr() - Searching for a Character in a String

    The strchr() function searches for the first occurrence of a character in a string. It returns a pointer to the first occurrence of the character or NULL if the character is not found.

    Syntax:

    char *strchr(const char *str, int c);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        char *ptr = strchr(str, 'W');  // Find the first occurrence of 'W'
        
        if (ptr != NULL) {
            printf("Character found: %c at position: %ld\n", *ptr, ptr - str);
        } else {
            printf("Character not found.\n");
        }
        
        return 0;
    }
    

    Explanation:

    • strchr(str, 'W') finds the first occurrence of 'W' in the string "Hello, World!". It returns a pointer to that character, and the program prints its position.

    Output:

    Character found: W at position: 7
    

    6. strstr() - Searching for a Substring

    The strstr() function searches for the first occurrence of a substring in a string. It returns a pointer to the first character of the found substring or NULL if the substring is not found.

    Syntax:

    char *strstr(const char *haystack, const char *needle);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World!";
        char *result = strstr(str, "World");
        
        if (result != NULL) {
            printf("Substring found at: %s\n", result);
        } else {
            printf("Substring not found.\n");
        }
        
        return 0;
    }
    

    Explanation:

    • strstr(str, "World") finds the first occurrence of the substring "World" in "Hello, World!" and returns a pointer to the beginning of the substring.

    Output:

    Substring found at: World!
    

    7. strtok() - Tokenizing a String

    The strtok() function is used to split a string into tokens based on delimiters. It modifies the original string by replacing delimiters with null characters.

    Syntax:

    char *strtok(char *str, const char *delim);
    

    Example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello, World! Welcome to C.";
        char *token = strtok(str, " ,.!");  // Delimiters: space, comma, dot, exclamation mark
        
        while (token != NULL) {
            printf("Token: %s\n", token);
            token = strtok(NULL, " ,.!");  // Get the next token
        }
        
        return 0;
    }
    

    Explanation:

    • strtok(str, " ,.!") breaks the string "Hello, World! Welcome to C." into tokens separated by spaces, commas, dots, and exclamation marks.
    • The function continues to tokenize the string in the loop until all tokens are processed.

    Output:

    Token: Hello
    Token: World
    Token: Welcome
    Token: to
    Token: C
    

    8. sprintf() - Formatting Strings

    The sprintf() function formats data and stores it as a string. It works similarly to printf(), but instead of printing to the console, it stores the result in a string.

    Syntax:

    int sprintf(char *str, const char *format, ...);
    

    Example:

    #include <stdio.h>
    
    int main() {
        char str[50];
        int age = 25;
        
        sprintf(str, "I am %d years old.", age);  // Format and store in str
        
        printf("%s\n", str);  // Output: I am 25 years old.
        
        return 0;
    }
    

    Explanation:

    • sprintf(str, "I am %d years old.", age) stores the formatted string "I am 25 years old." in str.

    Summary of Key String Functions in C

    • strlen(): Returns the length of a string.
    • strcpy(): Copies one string to another.
    • strcat(): Appends one string to another.
    • strcmp(): Compares two strings.
    • strchr(): Searches for a character in a string.
    • strstr(): Searches for a substring in a string.
    • strtok(): Tokenizes a string into smaller parts (tokens).
    • sprintf(): Formats and stores a formatted string.

    The <string.h> library is a powerful tool for manipulating strings in C, and it provides essential functions for handling text efficiently. Understanding these functions will allow you to perform a wide variety of string operations in your programs.

    ← Previous topic 25
    Characters and Strings: Strings and Characters, Character Handling Library
    Next topic 27 →
    Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals