Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Jun 2003
    Messaggi
    4,826

    [c++]std string replace

    come si fa in stl a fare il replace di una parte di stringa?
    ad es ho la string "pippo_001" e vorrei trasformarla in "pippo".
    forse sbaglio funzione?

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Se devi cancellare parte della stringa usa la erase()
    http://www.cplusplus.com/reference/s...ing/erase.html

    ES.
    codice:
       std::string test("pippo_001");
       test.erase(test.find_first_of('_'), test.end());
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

  3. #3
    Questa routine che ho scritto un po' di tempo fa dovrebbe gestire tutti i possibili casi.
    codice:
    //Replaces all the instances of search with replace in string; returns the number of substitutions done
    unsigned int ReplaceString(std::string & string,const std::string & search,const std::string & replace)
    {
    	unsigned int ret=0;
    	for(std::string::size_type pos=string.find(search);pos!=string.npos;ret++,pos=string.find(search,++pos))
    	{
    		if(search.length()>replace.length())
    			string.erase(pos,search.length()-replace.length());
    		if(search.length()<replace.length())
    			string.insert(pos,replace.length()-search.length(),_T(' '));
    		string.replace(pos,replace.length(),replace);
    	}
    	return ret;
    }
    Amaro C++, il gusto pieno dell'undefined behavior.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.