2010-06-27 5 views
1

j'ai aa tableau de caractères en C++ qui looke comme { 'a', 'b', 'c', 0,0,0,0}C++ recherche String.Replace()

maintenant im wrting il à un flux et je veux qu'il apparaisse comme "abc" avec quatre espaces instants du du néant Je suis principalement en utilisant std :: stiring et j'ai aussi boost. comment puis-je le faire en C++

basiquement Je pense que je cherche quelque chose comme

char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually... 
std::string newString(hellishCString, sizeof(hellishCString)); 

newString.Replace(0,' '); // not real C++ 

ar << newString; 
+0

Est-ce que 'std :: string' peut contenir des caractères null incorporés? Une autre option peut être d'utiliser 'std :: vector' à la place. – dreamlax

+1

@dreamlax: Oui, ils peuvent. – sbi

+0

@dreamlax: Oui, ils peuvent. La longueur de la chaîne est stockée indépendamment, donc il n'y a pas besoin de terminaison nulle et les caractères nuls ne sont pas traités spécialement. – Philipp

Répondre

10

Utilisation std::replace:

#include <string> 
#include <algorithm> 
#include <iostream> 

int main(void) { 
    char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually... 
    std::string newString(hellishCString, sizeof hellishCString); 
    std::replace(newString.begin(), newString.end(), '\0', ' '); 
    std::cout << '+' << newString << '+' << std::endl; 
} 
+0

Erreur erreur C2782: 'vide std :: remplacer (_FwdIt, _FwdIt, const & _Ty, const & _Ty)': paramètre modèle '_Ty' est ambigu –

+0

mon erreur, je l'ai essayé: std :: remplacer (groupString .begin(), groupString.end(), 0, ''); et 0 est évidemment int ... –

1

Une autre solution si vous remplacez un tableau par le vecteur

#include <vector> 
#include <string> 
#include <algorithm> 
#include <iostream> 


char replaceZero(char n) 
{ 
    return (n == 0) ? ' ' : n; 
} 

int main(int argc, char** argv) 
{ 
    char hellish[] = {'a','b','c',0,0,0,0}; 
    std::vector<char> hellishCString(hellish, hellish + sizeof(hellish));  
    std::transform(hellishCString.begin(), hellishCString.end(), hellishCString.begin(), replaceZero); 
    std::string result(hellishCString.begin(), hellishCString.end()); 
    std::cout << result; 
    return 0; 
}