Outils pour utilisateurs

Outils du site


lang:cpp:string

wstring

wstring est surtout utile pour Windows car toutes les appels de fonctions finissant par W en ont besoin.

#include <fstream>
#include <ios>
#include <codecvt>
 
std::wofstream out("file.txt", std::ios_base::out | std::ios_base::app);
const std::locale utf8_locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
out.imbue(utf8_locale);
// Verify that the file opened correctly
std::wstring s(L"contenu");
out << s << std::endl;

Multiplatform way to write a std::wstring into a file in C++ Archive du 23/05/2016 le 27/12/2019

  • Conversion entre string et wstring

Sous windows :

std::wstring s2ws(const std::string& s)
{
  int slength = (int)s.length() + 1;
  int len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
  std::wstring r(len, L'\0');
  MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, &r[0], len);
  return r;
}
 
std::string ws2s(const std::wstring& s)
{
  int slength = (int)s.length() + 1;
  int len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0); 
  std::string r(len, '\0');
  WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, &r[0], len, 0, 0); 
  return r;
}

Converting between std::wstring and std::string Archive du 29/01/2011 le 04/05/2023

stringstream

Le résultat ne va pas être le même si on donne à std::stringstream un int ou un char.

ss << static_cast<char>(1);

va donner \x1.

ss << static_cast<int>(1);

va donner 1.

consteval avec std::string_view

Ce n'est pas possible. Il faut travailler avec les char*.

#include <array>
#include <cstring>
 
template <class T, std::size_t N>
struct decayable_array : std::array<T, N> {
  constexpr operator const T*() const { return this->data(); }
};
 
template <std::size_t N>
consteval decayable_array<char, N> reverse(const char (&arr)[N]) {
  decayable_array<char, N> data{};
 
  for (std::size_t i = 0; i < N - 1; ++i) {
    data[N - i - 2] = arr[i];
  }
 
  return data;
}
 
int main() { return strlen(reverse("abc")); }
main:
  mov     eax, 3
  ret

Exemple godbolt

Split

string

std::istringstream f("denmark;sweden;india;us");
std::string s;    
while (getline(f, s, ';')) {
  // Résultat dans s.
}

Splitting a C++ std::string using tokens, e.g. “;” Archive du 02/03/2011 le 27/12/2019

string_view

std::vector<std::string_view>
splitSV(std::string_view strv, std::string_view delims = " ")
{
  std::vector<std::string_view> output;
  size_t first = 0;
 
  while (first < strv.size())
  {
    const auto second = strv.find_first_of(delims, first);
 
    if (first != second)
      output.emplace_back(strv.substr(first, second-first));
 
    if (second == std::string_view::npos)
      break;
 
    first = second + 1;
  }
 
  return output;
}

Speeding Up string_view String Split Implementation Archive du 30/07/2018 le 27/12/2019

lang/cpp/string.txt · Dernière modification : 2023/05/29 11:58 de root