Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
strcspn() in C
The strcspn() function in C counts the number of characters in the initial segment of a string that do not match any character from a second string. It is declared in the string.h header file and returns the length of the initial segment of the first string before the first occurrence of any character from the second string.
Syntax
size_t strcspn(const char *string1, const char *string2);
Parameters:
- string1 − The string to be scanned
- string2 − The string containing characters to search for in string1
Return Value: Returns the number of characters in the initial segment of string1 that do not match any character in string2.
Example 1: Basic Usage
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Helloworld!";
char str2[] = "work";
int result = strcspn(str1, str2);
printf("String 1: %s<br>", str1);
printf("String 2: %s<br>", str2);
printf("Number of characters before first match: %d<br>", result);
return 0;
}
String 1: Helloworld! String 2: work Number of characters before first match: 5
Example 2: No Match Found
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "programming";
char str2[] = "xyz";
int result = strcspn(str1, str2);
printf("String 1: %s<br>", str1);
printf("String 2: %s<br>", str2);
printf("Number of characters scanned: %d<br>", result);
printf("Length of str1: %lu<br>", strlen(str1));
return 0;
}
String 1: programming String 2: xyz Number of characters scanned: 11 Length of str1: 11
How It Works
The strcspn() function scans each character in string1 sequentially and checks if it matches any character in string2. It stops at the first match and returns the count of characters examined before that match. If no match is found, it returns the length of string1.
Key Points
- Returns the index position where the first matching character occurs
- If no characters match, returns the length of the first string
- Useful for input validation and string parsing operations
- Case-sensitive comparison
Conclusion
The strcspn() function is useful for finding the position of unwanted characters in a string. It helps in string validation and parsing by determining how many valid characters exist before encountering an invalid one.
