Cpp string replace all

std:: string::replace

Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents:

(1) string Copies str. (2) substring Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos). (3) c-string Copies the null-terminated character sequence (C-string) pointed by s. (4) buffer Copies the first n characters from the array of characters pointed by s. (5) fill Replaces the portion of the string by n consecutive copies of character c. (6) range Copies the sequence of characters in the range [first,last), in the same order. (7) initializer list Copies each of the characters in il, in the same order.

Parameters

str Another string object, whose value is copied.
pos Position of the first character to be replaced.
If this is greater than the string length, it throws out_of_range.
len Number of characters to replace (if the string is shorter, as many characters as possible are replaced).
A value of string::npos indicates all characters until the end of the string. subpos Position of the first character in str that is copied to the object as replacement.
If this is greater than str‘s length, it throws out_of_range.
sublen Length of the substring to be copied (if the string is shorter, as many characters as possible are copied).
A value of string::npos indicates all characters until the end of str. s Pointer to an array of characters (such as a c-string). n Number of characters to copy. c Character value, repeated n times. first, last Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last.
The function template argument InputIterator shall be an input iterator type that points to elements of a type convertible to char. il An initializer_list object.
These objects are automatically constructed from initializer list declarators.
size_t is an unsigned integral type (the same as member type string::size_type ).

Читайте также:  Эффекты перехода страниц

Return Value

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// replacing in a string int main () < std::string base="this is a test string."; std::string str2="n example"; std::string str3="sample phrase"; std::string str4="useful."; // replace signatures used in the same order as described above: // Using positions: 0123456789*123456789*12345 std::string str=base; // "this is a test string." str.replace(9,5,str2); // "this is an example string." (1) str.replace(19,6,str3,7,6); // "this is an example phrase." (2) str.replace(8,10,"just a"); // "this is just a phrase." (3) str.replace(8,6,"a shorty",7); // "this is a short phrase." (4) str.replace(22,1,3,'!'); // "this is a short phrase. " (5) // Using iterators: 0123456789*123456789* str.replace(str.begin(),str.end()-3,str3); // "sample phrase. " (1) str.replace(str.begin(),str.begin()+6,"replace"); // "replace phrase. " (3) str.replace(str.begin()+8,str.begin()+14,"is coolness",7); // "replace is cool. " (4) str.replace(str.begin()+12,str.end()-4,4,'o'); // "replace is cooool. " (5) str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful." (6) std::cout '\n'; return 0; >

Complexity

Iterator validity

Data races

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the string.

If s does not point to an array long enough, or if the range specified by [first,last) is not valid, it causes undefined behavior.

If pos is greater than the string length, or if subpos is greater than str‘s length, an out_of_range exception is thrown.
If the resulting string length would exceed the max_size, a length_error exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.

Читайте также:  If contains java example

See also

string::insert Insert into string (public member function) string::append Append to string (public member function) string::substr Generate substring (public member function) string::erase Erase characters from string (public member function) string::assign Assign content to string (public member function)

Источник

Replace all occurrences of a character in String in C++

In this article, we will discuss different ways to replace all occurrences of a character from a string with an another character in C++.

Table Of Contents

We want to replace all the occurrence of character ‘e’ with ‘P’ in this string. After that, the final string should be like,

There are different ways to this. Let’s discuss them one by one.

Frequently Asked:

Using STL Algorithm std::replace()

In C++, the STL provides a function to replace() to change the contents of an iterable container. As string is a collection of characters, so we can use the std::replace() function to replace all the occurrences of character ‘e’ with character ‘P’ in the string. For this, we need to pass the following arguments to the std::replace() function,

  • Iterator pointing to the start of string.
  • Iterator pointing to the end of string.
  • Character to be replaced i.e. ‘e’.
  • Replacement character i.e. ‘P’.

It will replace all occurrences of character ‘e’ with the characyter ‘P’ in the string.

Are you a C++ programmer eager to step up your game?

Master the intricacies of C++/C++11/C++20 with our handpicked list of the Best Courses to Learn Modern C++11, C++17 and C++20. Sharpen your skills, conquer complex algorithms, and stand out in your professional or academic sphere.

This isn’t just about learning — it’s about transforming into the programmer you aspire to be. So, why wait?

Your leap towards programming excellence is just a click away.

For example,

#include #include #include int main() < std::string strValue = "Some extra text"; const char toBeReplaced = 'e'; const char replacement = 'P'; // Replace all occurrences of character 'e' with 'P' std::replace(strValue.begin(), strValue.end(), toBeReplaced, replacement); std::cout

It replaced all occurrences of character ‘e’ in the string with the the character ‘P’.

Using string::replace() and find()

We can look for the index positions of given character in the string using find() function and replace them using the string::replace() function.

  • Find the Index position of given character in the string using string::find() function.
  • While the index position is valid,
    • Replace the character at that index position with the replacement character using std::replace()
    • Again find the index position of given character in the string using string::find() function.

    Let’s understand this with an example,

    #include #include int main() < std::string strValue = "Some extra text"; const char toBeReplaced = 'e'; const char replacement = 'P'; size_t pos = strValue.find(toBeReplaced); // Replace all occurrences of character 'e' with 'P' while( pos != std::string::npos) < strValue.replace(pos, 1, 1, replacement); pos = strValue.find(toBeReplaced); >std::cout

    We looked for all the index positions of character ‘e’ in the string using find(). Then we replaced the characters at those index positions with the character ‘P’ using the string::replace() function. For replacing a character at a time using the string::replace() function, we need to pass following arguments,

    • Index position in string from where it needs to start the replacement.
    • Number of characters that need to be replaced. In our case it was 1.
    • Number of characters to copy. In our case it was 1.
    • Character value, that will be repeated n times. In our case it was ‘P’.

    It replaced all the occurrences of character ‘e’ with the ‘P’ in the string.

    Using Iteration

    What if we have a char array instead of string?

    Iterate over all the characters in the char array and for each character check if it is equal to the character that need to replaced. If yes, then replace the value at that index position in string / char array with the replacement character.

    For example,

    #include int main() < char strValue[] = "Some extra text"; const char toBeReplaced = 'e'; const char replacement = 'P'; size_t len = sizeof(strValue) / sizeof(strValue[0]); // Iterate over all characters in the char array for (int i = 0; i < len; i++) < // Check if character needs to be replaced if (strValue[i] == toBeReplaced) < // Replace the character strValue[i] = replacement; >> std::cout

    We replaced all the occurrences of the character ‘e’ with ‘P’ in the string.

    We learned about three different ways to replace all occurrences of a character in a string in C++.

    Share your love

    Leave a Comment Cancel Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Terms of Use

    Disclaimer

    Copyright © 2023 thisPointer

    To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

    Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

    The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

    The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

    The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

    The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

    Источник

    Почему у std::string нет человеческого replace?

    Но несколько странно, что в XXI веке для такой простой задачи надо так много писать.

    Вопрос один: почему оно так?
    Вроде уже и C++ 11/14/17 появились, а воз и ныне там 🙁

    Средний 3 комментария

    myjcom

    void replace_all(string& src, const string a, const string b) < auto pos = src.find(a); while(pos != string::npos) < src.replace(pos, a.size(), b); pos = src.find(a, pos); >> string s = "xxx yyy zzz xxx yyy zzz"; replace_all(s, "xxx", "replacedxxx");

    нужно пихать в basic_string?

    в более сложных случаях https://en.cppreference.com/w/cpp/algorithm/search
    тем более в С++17 появился boyer_moore_searcher и т.п.

    Roman, Плохой программист Джон сделал ошибку в коде, из-за которой каждый пользователь программы был вынужден потратить в среднем 15 минут времени на поиск обхода возникшей проблемы. Пользователей было 10 миллионов. Всего впустую потрачено 150 миллионов минут = 2.5 миллиона часов. Если человек спит 8 часов в сутки, то на сознательную деятельность у него остается 16 часов. То есть Джон уничтожил 156250 человеко-дней ≈ 427.8 человеко-лет. Средний мужчина живет 64 года, значит Джон убил примерно 6 целых 68 сотых человека.

    Как тебе спится, Джон — серийный программист?

    Если хотя бы каждый второй разраб вынужден копипастить бедную несчастную функцию replace_all, то лучше её таки иметь внутри STL.

    За Бойера-Мура спасибо, я не знал, что его дотащили до стандарта.

    Источник

Оцените статью