From e3daf7ef1fdb6b9d31a4eeaf343630ccbeb4a4b0 Mon Sep 17 00:00:00 2001 From: Lynix Date: Sat, 3 Dec 2016 00:34:55 +0100 Subject: [PATCH] Core/String: Add GetCharacterPosition method --- include/Nazara/Core/String.hpp | 1 + src/Nazara/Core/String.cpp | 39 +++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/include/Nazara/Core/String.hpp b/include/Nazara/Core/String.hpp index 765ef8b85..ba7f34ff7 100644 --- a/include/Nazara/Core/String.hpp +++ b/include/Nazara/Core/String.hpp @@ -82,6 +82,7 @@ namespace Nz char* GetBuffer(); std::size_t GetCapacity() const; + std::size_t GetCharacterPosition(std::size_t characterIndex) const; const char* GetConstBuffer() const; std::size_t GetLength() const; std::size_t GetSize() const; diff --git a/src/Nazara/Core/String.cpp b/src/Nazara/Core/String.cpp index 5019f0885..ac01bf92c 100644 --- a/src/Nazara/Core/String.cpp +++ b/src/Nazara/Core/String.cpp @@ -2094,6 +2094,43 @@ namespace Nz return m_sharedString->capacity; } + /*! + * \brief Gets the index where a character begin + * + * Iterate through the string to find the starting position of a specific character index + * This is useful because non-ASCII characters may be encoded using multiple bytes. + * + * \param characterIndex Index of the character to search for + * + * \return Starting index + */ + std::size_t String::GetCharacterPosition(std::size_t characterIndex) const + { + const char* ptr = m_sharedString->string.get(); + const char* end = &m_sharedString->string[m_sharedString->size]; + + try + { + utf8::advance(ptr, characterIndex, end); + + return ptr - m_sharedString->string.get(); + } + catch (utf8::not_enough_room& e) + { + // Returns npos + } + catch (utf8::exception& e) + { + NazaraError("UTF-8 error: " + String(e.what())); + } + catch (std::exception& e) + { + NazaraError(e.what()); + } + + return npos; + } + /*! * \brief Gets the raw buffer * \return Raw buffer @@ -5948,7 +5985,7 @@ namespace std char c; - for (;;) + for (;;) { is.get(c); if (c != delim && c != '\0')