From ac49710a12a44a7c6ac618d82c5c685b473b1cd2 Mon Sep 17 00:00:00 2001 From: Jaroslav Louma Date: Wed, 29 Nov 2023 21:14:18 +0100 Subject: [PATCH] Added `String_charAt` + tests --- include/internal/String.h | 9 +++++++++ src/internal/String.c | 13 +++++++++++++ test/internal/String.test.c | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/include/internal/String.h b/include/internal/String.h index f0138dd..1231a6a 100644 --- a/include/internal/String.h +++ b/include/internal/String.h @@ -105,6 +105,15 @@ bool String_endsWith(String *string, char *value); */ long String_indexOf(String *string, char *value); +/** + * Returns the character at a given index in a String. + * + * @param string The String to get the character from. + * @param index The index of the character to get. (negative values start from the end) + * @return The character at the given index. + */ +char String_charAt(String *string, signed long index); + /** * Copies the contents of the String to a given buffer of a given length. * diff --git a/src/internal/String.c b/src/internal/String.c index 439c0df..091d05a 100644 --- a/src/internal/String.c +++ b/src/internal/String.c @@ -218,6 +218,19 @@ long String_indexOf(String *string, char *value) { return result - string->value; } +char String_charAt(String *string, signed long index) { + if(!string) return '\0'; + if(!string->value) return '\0'; + + // Resolve negative indices + if(index < 0) index = string->length + index; + + // Index out of bounds + if(index < 0 || index > (signed long)string->length) return '\0'; + + return string->value[index]; +} + void String_copy(String *string, char *dest, size_t length) { if(!string) return; if(!dest) return; diff --git a/test/internal/String.test.c b/test/internal/String.test.c index e5e2a91..30713f2 100644 --- a/test/internal/String.test.c +++ b/test/internal/String.test.c @@ -521,3 +521,38 @@ DESCRIBE(fromRange, "String_fromRange") { EXPECT_NULL(str); }) } + +DESCRIBE(charAt, "String_charAt") { + String *str = NULL; + + TEST("Simple charAt", { + str = String_alloc("Hello, World!"); + EXPECT_EQUAL_CHAR(String_charAt(str, 0), 'H'); + EXPECT_EQUAL_CHAR(String_charAt(str, 3), 'l'); + EXPECT_EQUAL_CHAR(String_charAt(str, 6), ' '); + EXPECT_EQUAL_CHAR(String_charAt(str, 9), 'r'); + EXPECT_EQUAL_CHAR(String_charAt(str, 12), '!'); + }) + + TEST("Single character charAt", { + str = String_alloc("A"); + EXPECT_EQUAL_CHAR(String_charAt(str, 0), 'A'); + }) + + TEST("Empty charAt", { + str = String_alloc(""); + EXPECT_EQUAL_CHAR(String_charAt(str, 0), '\0'); + }) + + TEST("Negative index", { + str = String_alloc("Hello, World!"); + EXPECT_EQUAL_CHAR(String_charAt(str, -1), '!'); + EXPECT_EQUAL_CHAR(String_charAt(str, -13), 'H'); + }) + + TEST("Out of bounds charAt", { + str = String_alloc("Hello, World!"); + EXPECT_EQUAL_CHAR(String_charAt(str, 13), '\0'); + EXPECT_EQUAL_CHAR(String_charAt(str, -14), '\0'); + }) +}