Add a Chomp feature to String construction that removes a trailing newline.

This will be useful in many situations.
This commit is contained in:
Andreas Kling 2018-11-07 00:19:35 +01:00
parent 90bab5ea71
commit 8135952832
4 changed files with 19 additions and 9 deletions

View file

@ -65,6 +65,8 @@ Vector<String> String::split(const char separator) const
size_t taillen = length() - substart;
if (taillen != 0)
v.append(substring(substart, taillen));
if (characters()[length() - 1] == separator)
v.append(empty());
return v;
}

View file

@ -24,13 +24,13 @@ public:
{
}
String(const char* cstring)
: m_impl(StringImpl::create(cstring))
String(const char* cstring, ShouldChomp shouldChomp = NoChomp)
: m_impl(StringImpl::create(cstring, shouldChomp))
{
}
String(const char* cstring, size_t length)
: m_impl(StringImpl::create(cstring, length))
String(const char* cstring, size_t length, ShouldChomp shouldChomp = NoChomp)
: m_impl(StringImpl::create(cstring, length, shouldChomp))
{
}

View file

@ -42,7 +42,7 @@ RetainPtr<StringImpl> StringImpl::createUninitialized(size_t length, char*& buff
return newStringImpl;
}
RetainPtr<StringImpl> StringImpl::create(const char* cstring, size_t length)
RetainPtr<StringImpl> StringImpl::create(const char* cstring, size_t length, ShouldChomp shouldChomp)
{
if (!cstring)
return nullptr;
@ -54,15 +54,20 @@ RetainPtr<StringImpl> StringImpl::create(const char* cstring, size_t length)
auto newStringImpl = createUninitialized(length, buffer);
memcpy(buffer, cstring, length * sizeof(char));
if (shouldChomp && buffer[length - 1] == '\n') {
buffer[length - 1] = '\0';
--newStringImpl->m_length;
}
return newStringImpl;
}
RetainPtr<StringImpl> StringImpl::create(const char* cstring)
RetainPtr<StringImpl> StringImpl::create(const char* cstring, ShouldChomp shouldChomp)
{
if (!cstring)
return nullptr;
return create(cstring, strlen(cstring));
return create(cstring, strlen(cstring), shouldChomp);
}
static inline bool isASCIILowercase(char c)

View file

@ -6,11 +6,13 @@
namespace AK {
enum ShouldChomp { NoChomp, Chomp };
class StringImpl : public Retainable<StringImpl> {
public:
static RetainPtr<StringImpl> createUninitialized(size_t length, char*& buffer);
static RetainPtr<StringImpl> create(const char* cstring);
static RetainPtr<StringImpl> create(const char* cstring, size_t length);
static RetainPtr<StringImpl> create(const char* cstring, ShouldChomp = NoChomp);
static RetainPtr<StringImpl> create(const char* cstring, size_t length, ShouldChomp = NoChomp);
RetainPtr<StringImpl> toLowercase() const;
RetainPtr<StringImpl> toUppercase() const;
@ -50,3 +52,4 @@ private:
}
using AK::StringImpl;
using AK::Chomp;