summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJonah Alligood <jonahisadev@gmail.com>2019-10-15 23:29:22 -0500
committerAndreas Kling <awesomekling@gmail.com>2019-10-17 14:39:57 +0200
commita544fded88d8183d0513b3de8c5917cb51f3a307 (patch)
tree79f52cc08d2a04818e3f7e252f27faa5bad62e01
parentc13be2c7eab770d0dd4431077910cdba9396d773 (diff)
downloadserenity-a544fded88d8183d0513b3de8c5917cb51f3a307.zip
LibC: strtok is now implemented (string.h)
-rw-r--r--Libraries/LibC/string.cpp47
1 files changed, 44 insertions, 3 deletions
diff --git a/Libraries/LibC/string.cpp b/Libraries/LibC/string.cpp
index 982419358e..075a78bea9 100644
--- a/Libraries/LibC/string.cpp
+++ b/Libraries/LibC/string.cpp
@@ -457,9 +457,50 @@ char* strpbrk(const char* s, const char* accept)
char* strtok(char* str, const char* delim)
{
- (void)str;
- (void)delim;
- ASSERT_NOT_REACHED();
+ static char* saved_str;
+
+ if (!str) {
+ if (!saved_str)
+ return nullptr;
+ str = saved_str;
+ }
+
+ size_t token_start = 0;
+ size_t token_end = 0;
+
+ for (size_t i = 0; i < strlen(str); ++i) {
+ bool is_delim = false;
+ for (size_t j = 0; j < strlen(delim); ++j) {
+ if (str[i] == delim[j]) {
+ is_delim = true;
+ ++token_start;
+ break;
+ }
+ }
+ if (!is_delim) break;
+ }
+
+ if (strlen(&str[token_start]) == 0)
+ return nullptr;
+
+ for (size_t i = 0; i < strlen(delim); ++i) {
+ char* delim_ptr = strchr(&str[token_start], delim[i]);
+ if (!delim_ptr)
+ continue;
+
+ size_t delim_offset = static_cast<size_t>(delim_ptr - str);
+ if (!token_end || token_end > delim_offset)
+ token_end = delim_offset;
+ }
+
+ if (token_end == 0) {
+ saved_str = nullptr;
+ return &str[token_start];
+ }
+
+ saved_str = &str[token_end + 1];
+ str[token_end] = '\0';
+ return &str[token_start];
}
int strcoll(const char* s1, const char* s2)