ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›String Functions, Library Functions
    Programming FundamentalsTopic 26 of 39

    String Functions, Library Functions

    7 minread
    1,225words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,225
      Code examples0
      DifficultyIntermediate