STRCSPN()

this function determines the length of the initial segment of a string that consists entirely of characters not found in a specified set. it is frequently used with fgets() to easily find and remove the trailing newline character that fgets() often includes in the input string.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main() {
    char str[100];
    int flag = 1;
    
    // Your code goes here
    do{
        // Prompt the user for input until a non-empty string is entered
        fgets(str, sizeof(str), stdin);
        
        //finds the newline character (if it exists) and then overwrites it with a 
        //null terminator
        str[strcspn(str,"\n")] = '\0';
        if (strlen(str) == 0){
        printf("Invalid Input...Try again!\n");

        }
        else{
            flag = 0;
        }
    }while(flag);
    
    // Convert to uppercase using toupper()
    int i = 0;
    while (str[i] != '\0') {
        str[i] = toupper(str[i]);
        i++;
    }

    // Print the uppercase string
    printf("Uppercase string: %s\n", str);

    // Convert to lowercase using tolower()
    i = 0;
    while (str[i] != '\0') {
        str[i] = tolower(str[i]);
        i++;
    }

    // Print the lowercase string
    printf("Lowercase string: %s\n", str);

    return 0;
}


 * the strcspn(str, "\n") line scans the str array from the beginning
    - It looks for the first occurrence of any character from the second argument, 
      which is "\n" (meaning just the newline character).
    - It returns the index (position) of the first newline character it finds. If no 
      newline is found (e.g., the input was too long and fgets didn't read the newline,
      or the user just pressed Enter without typing anything), it returns the length of 
      the entire string str
      
 * the str[ ... ] line refers to the character at the specified position within the
   str array

 * the = '\0' line assigns the null terminator character (\0) to the character at that X 
   position




W/O STRCSPN()

#include <stdio.h>
#include <string.h> // For strlen()

int main() {
    char buffer[100]; // Example buffer

    printf("Enter a string: ");
    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        // Get the length of the string
        size_t len = strlen(buffer);

        // Check if the last character is a newline and the string is not empty
        if (len > 0 && buffer[len - 1] == '\n') {
            buffer[len - 1] = '\0'; // Replace the newline with a null terminator
        }
    }

    printf("String without newline: \"%s\"\n", buffer);

    return 0;
}

Last updated