mirror of
https://github.com/theoludwig/libcproject.git
synced 2024-11-08 22:31:31 +01:00
feat: add string_position_of
This commit is contained in:
parent
9bb21e070f
commit
ec6e748d24
11
lib/string.c
11
lib/string.c
@ -384,3 +384,14 @@ bool string_ends_with(const string_t string, const string_t prefix) {
|
||||
}
|
||||
return ends_with;
|
||||
}
|
||||
|
||||
size_t string_position_of(const string_t string, const char character) {
|
||||
size_t position_found = 0;
|
||||
size_t string_length = string_get_length(string);
|
||||
for (size_t index = 0; index < string_length && position_found == 0; index++) {
|
||||
if (string[index] == character) {
|
||||
position_found = index + 1;
|
||||
}
|
||||
}
|
||||
return position_found;
|
||||
}
|
||||
|
11
lib/string.h
11
lib/string.h
@ -264,4 +264,15 @@ bool string_starts_with(const string_t string, const string_t prefix);
|
||||
*/
|
||||
bool string_ends_with(const string_t string, const string_t prefix);
|
||||
|
||||
/**
|
||||
* @brief Returns the position (index + 1) within the string of the first occurrence of the specified substring (0 if not found).
|
||||
*
|
||||
* @param string
|
||||
* @param substring
|
||||
* @return size_t
|
||||
* @example string_position_of("hello world", "e") // 2
|
||||
* @since v4.2.0
|
||||
*/
|
||||
size_t string_position_of(const string_t string, const char character);
|
||||
|
||||
#endif
|
||||
|
@ -25,6 +25,7 @@ void string_test() {
|
||||
string_get_last_occurence_of_character_test();
|
||||
string_starts_with_test();
|
||||
string_ends_with_test();
|
||||
string_position_of_test();
|
||||
}
|
||||
|
||||
void string_get_length_test() {
|
||||
@ -277,3 +278,14 @@ void string_ends_with_test() {
|
||||
assert(!string_ends_with("abcdef", "bcd"));
|
||||
assert(!string_ends_with("abcdef", "abcdefg"));
|
||||
}
|
||||
|
||||
void string_position_of_test() {
|
||||
assert(string_position_of("hello world", 'e') == 2);
|
||||
assert(string_position_of("abcdef", 'a') == 1);
|
||||
assert(string_position_of("abcdef", 'b') == 2);
|
||||
assert(string_position_of("abcdef", 'c') == 3);
|
||||
assert(string_position_of("abcdef", 'd') == 4);
|
||||
assert(string_position_of("abcdef", 'e') == 5);
|
||||
assert(string_position_of("abcdef", 'f') == 6);
|
||||
assert(string_position_of("abcdef", 'g') == 0);
|
||||
}
|
||||
|
@ -58,4 +58,6 @@ void string_starts_with_test();
|
||||
|
||||
void string_ends_with_test();
|
||||
|
||||
void string_position_of_test();
|
||||
|
||||
#endif
|
||||
|
Loading…
Reference in New Issue
Block a user