Skip to content

Instantly share code, notes, and snippets.

@kinnou02
Last active December 30, 2015 19:09
Show Gist options
  • Save kinnou02/7872124 to your computer and use it in GitHub Desktop.
Save kinnou02/7872124 to your computer and use it in GitHub Desktop.
multibyte compliant substr
std::string substr(const std::string& str, size_t nb){
std::stringstream result;
auto it = str.begin();
unsigned char c;
size_t count = 0;
while(it != str.end() && count < nb){
c = *it;
result << c;
if(c >= 0xc0){
++it;
c = *it;
while((c & 0xc0) == 0x80 && it != str.end()){
result << c;
++it;
c = *it;
}
}else{
++it;
}
++count;
}
return result.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment