'C Program- How do you find the index of any character in a string? [closed]
For example, in a string, you'll be asked to find and print the index of a capital character:
char str[100] = "helloWorld";
the capital letter is found at index 5 so printf("Index of capital letter: Index %d") in which %d should be 5
How do you create a code to print the index?
Solution 1:[1]
Use strcspn():
Synopsis
1
#include <string.h> size_t strcspn(const char *s1, const char *s2);Description
2 The
strcspnfunction computes the length of the maximum initial segment of the string pointed to bys1which consists entirely of characters not from the string pointed to bys2.Returns
3 The strcspn function returns the length of the segment.
For example:
// get the index of the first upper-case character
// return ( ssize_t ) -1 if there are none
ssize_t firstUpperCase( const char *str )
{
ssize_t index = strcspn( str, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
if ( index >= strlen( str )
{
index = ( ssize_t ) -1;
}
return( index );
}
Solution 2:[2]
To locate the first uppercase letter in the string, you must use a loop:
#include <ctype.h>
#include <stdio.h>
int main() {
char str[100] = "helloWorld";
for (int i = 0; str[i] != '\0'; i++) {
if (isupper((unsigned char)str[i]) {
printf("Index of capital letter '%c': %d\n", str[i], i);
return 0;
}
}
printf("No capital letter\n");
return 1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew Henle |
| Solution 2 | chqrlie |
