Замена символов C ++ - PullRequest
       14

Замена символов C ++

8 голосов
/ 30 ноября 2009

Каков наилучший способ замены символов в строке?

В частности:

"This,Is A|Test" ----> "This_Is_A_Test"

Я хочу заменить все запятые, пробелы и "|" с подчеркиванием.

(У меня есть доступ к Boost.)

Ответы [ 7 ]

16 голосов
/ 30 ноября 2009

Вы можете использовать стандартный алгоритм replace_if, за исключением того, что предикат довольно сложен (выражается в соответствии с текущим стандартом C ++ и без лямбды).

Вы можете написать свой собственный или использовать is_any_of из строковых алгоритмов boost, поэтому:

#include <algorithm>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>

int main()
{
    std::string s("This,Is A|Test");
    std::replace_if(s.begin(), s.end(), boost::is_any_of(", |"), '_');
    std::cout << s << '\n';
}
11 голосов
/ 30 ноября 2009

Вы можете использовать алгоритм STL replace_if .

9 голосов
/ 30 ноября 2009

Как указано в других ответах, вы можете использовать различные replace методы. Однако у этих подходов есть обратная сторона сканирования строки несколько раз (по одному разу для каждого символа). Я бы порекомендовал использовать собственный метод замены, если вам важна скорость:

void beautify(std::string &s) {
    int i;
    for (i = 0; i < s.length(); ++i) {
        switch (s[i]) {
        case ' ':
        case ',':
        case '|':
            s[i] = '_';
        }
    }
}
3 голосов
/ 30 ноября 2009

РЕДАКТИРОВАТЬ: Как сказал Space_C0wb0y , replace_if определенно лучше. Вот пример более простого примера кода:

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

bool isBad(char c)
{
 const string bad_chars = "|, ";
 return (bad_chars.find(c) != string::npos);
}

int main()
{
 string str = "This,Is A|Test";

 // Replace!
 replace_if(str.begin(),str.end(),isBad,'_');

 cout<<str<<endl; 
 return 0;
}

СТАРЫЙ ОТВЕТ:

Используйте std :: replace на std :: find_first_of

2 голосов
/ 30 ноября 2009

boost :: replace_all (s, old, new);

0 голосов
/ 30 ноября 2009

Я писал это, когда Space_C0wb0y опубликовал свой ответ, который является правильным ответом на ваш вопрос. Это немного сложнее, но обрабатывает больше возможных замен.

(извините, не скомпилировано / протестировано)

class MyReplacer
{
  friend std::ostream& operator<<(std::ostream& os, const MyReplacer& Repl);
  public:
    MyReplacer(char c) : ch(c) {}
  private:
    char ch;
};

std::ostream& operator<<(std::ostream& os, const MyReplacer& Repl)
{
  switch (Repl.ch)
  {
    case '|':
    case ' ':
    case ',': os << '_'; break;
    default: os << Repl.ch;
  }
  return os;
}


std::ostringstream oss;
std::copy(str.begin(), str.end(), std::ostream_iterator<MyReplacer>(oss));
std::string result = oss.str();
0 голосов
/ 30 ноября 2009

Стандартная библиотека C ++ также имеет доступ к этим функциям без использования BOOST. См. заменить C ++ Ссылка . Это лучший способ? Я думаю, что это до обсуждения. Для замены нескольких / разных символов вам, возможно, придется вызывать метод замены несколько раз.

#include <string>
    string& replace( size_type index, size_type num, const string& str );
    string& replace( size_type index1, size_type num1, const string& str, size_type index2, size_type num2 );
    string& replace( size_type index, size_type num, const Char* str );
    string& replace( size_type index, size_type num1, const Char* str, size_type num2 );
    string& replace( size_type index, size_type num1, size_type num2, Char ch);

    string& replace( iterator start, iterator end, const string& str );
    string& replace( iterator start, iterator end, const Char* str );
    string& replace( iterator start, iterator end, const Char* str, size_type num );
    string& replace( iterator start, iterator end, size_type num, Char ch );
    string& replace( iterator start, iterator end, input_iterator start2, input_iterator end2 );

Пример программы :

// replacing in a string
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string base="this is a test string.";
  string str2="n example";
  string str3="sample phrase";
  string str4="useful.";

  // function versions used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  string str=base;                // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string."
  str.replace(19,6,str3,7,6);     // "this is an example phrase."
  str.replace(8,10,"just all",6); // "this is just a phrase."
  str.replace(8,6,"a short");     // "this is a short phrase."
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"

  // Using iterators:                      0123456789*123456789*
  string::iterator it = str.begin();   //  ^
  str.replace(it,str.end()-3,str3);    // "sample phrase!!!"
  str.replace(it,it+6,"replace it",7); // "replace phrase!!!"
  it+=8;                               //          ^
  str.replace(it,it+6,"is cool");      // "replace is cool!!!"
  str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!"
  it+=3;                               //             ^
  str.replace(it,str.end(),str4.begin(),str4.end());
                                       // "replace is useful."
  cout << str << endl;
  return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...