--- nono/lib/mystring.cpp 2026/04/29 17:04:54 1.1.1.4 +++ nono/lib/mystring.cpp 2026/04/29 17:04:57 1.1.1.5 @@ -48,11 +48,30 @@ void rtrim(char *str) { char *p = strchr(str, '\0'); - while (--p >= str && (isspace((int)*p) || *p == '\r' || *p == '\n')) { + while (--p >= str && isspace((int)*p)) { *p = '\0'; } } +// 文字列 str から先頭と末尾の連続する空白文字を取り除いた新しい文字列を返す。 +std::string +string_trim(const std::string& str) +{ + int s = 0; + int e = str.size(); + + for (; s < e; s++) { + if (!isspace(str[s])) + break; + } + for (e--; e >= s; e--) { + if (!isspace(str[e])) + break; + } + + return str.substr(s, e - s + 1); +} + // 文字列 src 中の ASCII 大文字を小文字にした新しい文字列を返す。 std::string string_tolower(const std::string& src) @@ -88,11 +107,25 @@ starts_with_ignorecase(const std::string // 文字列 str (長さ len) を文字 c で分割したリストを返す。 std::vector -string_split(const char *str, int len, char c) +string_split(const char *str, int len, char c, int nlimit) { std::vector list; - for (int pos = 0, end = 0 ; pos < len; pos = end + 1) { + // 空文字列なら空リスト + if (len == 0) { + return list; + } + + int pos = 0; + int end = 0; + + for (; ; pos = end + 1) { + // 上限に達するならこれ以降は一要素として返す + if (nlimit > 0 && list.size() >= nlimit - 1) { + list.emplace_back(str + pos, len - pos); + break; + } + const char *p = strchr(str + pos, c); if (p) { end = p - str; @@ -101,6 +134,8 @@ string_split(const char *str, int len, c } list.emplace_back(str + pos, end - pos); + if (p == NULL) + break; } return list;