Core/String: Add GetCharacterPosition method

This commit is contained in:
Lynix 2016-12-03 00:34:55 +01:00
parent 370cdb4799
commit e3daf7ef1f
2 changed files with 39 additions and 1 deletions

View File

@ -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;

View File

@ -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')