Added ability to split FString on tokens

https://forum.zdoom.org/viewtopic.php?t=58114
This commit is contained in:
alexey.lysiuk 2017-10-28 11:26:21 +03:00
parent da94008f39
commit 3b3f2e20cc
2 changed files with 54 additions and 0 deletions

View file

@ -1162,6 +1162,49 @@ void FString::ReallocBuffer (size_t newlen)
}
}
TArray<FString> FString::Split(const FString &delimiter, const EmptyTokenType keepEmpty) const
{
return Split(delimiter.GetChars(), keepEmpty);
}
TArray<FString> FString::Split(const char *const delimiter, const EmptyTokenType keepEmpty) const
{
TArray<FString> tokens;
Split(tokens, delimiter, keepEmpty);
return tokens;
}
void FString::Split(TArray<FString>& tokens, const FString &delimiter, EmptyTokenType keepEmpty) const
{
Split(tokens, delimiter.GetChars(), keepEmpty);
}
void FString::Split(TArray<FString>& tokens, const char *delimiter, EmptyTokenType keepEmpty) const
{
assert(nullptr != delimiter);
const long selfLen = static_cast<long>(Len());
const long delimLen = static_cast<long>(strlen(delimiter));
long lastPos = 0;
while (lastPos <= selfLen)
{
long pos = IndexOf(delimiter, lastPos);
if (-1 == pos)
{
pos = selfLen;
}
if (pos != lastPos || TOK_KEEPEMPTY == keepEmpty)
{
tokens.Push(FString(GetChars() + lastPos, pos - lastPos));
}
lastPos = pos + delimLen;
}
}
// Under Windows, use the system heap functions for managing string memory.
// Under other OSs, use ordinary memory management instead.

View file

@ -312,6 +312,17 @@ public:
int CompareNoCase(const FString &other, int len) const { return strnicmp(Chars, other.Chars, len); }
int CompareNoCase(const char *other, int len) const { return strnicmp(Chars, other, len); }
enum EmptyTokenType
{
TOK_SKIPEMPTY = 0,
TOK_KEEPEMPTY = 1,
};
TArray<FString> Split(const FString &delimiter, EmptyTokenType keepEmpty = TOK_KEEPEMPTY) const;
TArray<FString> Split(const char *delimiter, EmptyTokenType keepEmpty = TOK_KEEPEMPTY) const;
void Split(TArray<FString>& tokens, const FString &delimiter, EmptyTokenType keepEmpty = TOK_KEEPEMPTY) const;
void Split(TArray<FString>& tokens, const char *delimiter, EmptyTokenType keepEmpty = TOK_KEEPEMPTY) const;
protected:
const FStringData *Data() const { return (FStringData *)Chars - 1; }
FStringData *Data() { return (FStringData *)Chars - 1; }