Browse Source

add methods for trimming \r\n from the end of a string

add:
void trim_last_new_lines(std::string & str, bool check_carriage_return_too = true);
void trim_last_new_lines(std::wstring & str, bool check_carriage_return_too = true);
master
Tomasz Sowa 4 months ago
parent
commit
aa97fe2811
  1. 14
      src/convert/text.cpp
  2. 2
      src/convert/text.h
  3. 14
      src/convert/text_private.h

14
src/convert/text.cpp

@ -5,7 +5,7 @@
*/
/*
* Copyright (c) 2017-2021, Tomasz Sowa
* Copyright (c) 2017-2022, Tomasz Sowa
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@ -532,6 +532,18 @@ void trim(std::wstring & str, wchar_t c)
}
void trim_last_new_lines(std::string & str, bool check_carriage_return_too)
{
pt_private::trim_last_generic(str, '\n', check_carriage_return_too, '\r');
}
void trim_last_new_lines(std::wstring & str, bool check_carriage_return_too)
{
pt_private::trim_last_generic(str, '\n', check_carriage_return_too, '\r');
}
}

2
src/convert/text.h

@ -201,6 +201,8 @@ void trim_last(std::wstring & str, wchar_t c);
void trim(std::string & str, wchar_t c);
void trim(std::wstring & str, wchar_t c);
void trim_last_new_lines(std::string & str, bool check_carriage_return_too = true);
void trim_last_new_lines(std::wstring & str, bool check_carriage_return_too = true);

14
src/convert/text_private.h

@ -5,7 +5,7 @@
*/
/*
* Copyright (c) 2021, Tomasz Sowa
* Copyright (c) 2021-2022, Tomasz Sowa
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@ -367,24 +367,24 @@ size_t i;
template<typename StringType>
void trim_last_generic(StringType & s, wchar_t c)
void trim_last_generic(StringType & s, wchar_t c, bool has_c2 = false, wchar_t c2 = 0)
{
size_t i;
if( s.empty() )
return;
// looking for the 'c' characters at the end
for(i=s.size()-1 ; i>0 && s[i]==c ; --i);
// looking for the 'c' or 'c2' (if defined) characters at the end
for(i=s.size()-1 ; i>0 && (s[i]==c || (has_c2 && s[i]==c2)) ; --i);
if( i==0 && s[i]==c )
if( i==0 && (s[i]==c || (has_c2 && s[i]==c2)) )
{
// the whole string has the 'c' characters
// the whole string has the 'c' and 'c2' characters
s.clear();
return;
}
// deleting 'c' characters at the end
// deleting 'c' and 'c2' characters at the end
if( i != s.size() - 1 )
s.erase(i+1, StringType::npos);
}

Loading…
Cancel
Save