Home >Backend Development >C++ >How to Replace Substrings in C ?

How to Replace Substrings in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 17:15:14170browse

How to Replace Substrings in C  ?

Replace substring with another substring in C

In C , replacing a substring with another substring can be achieved using various functions. Let's explore some of these options:

std::regex_replace (C 11 and later)

This function takes a regular expression as an argument and performs a search and replace operation on the input string. Here's an example:

#include <string>
#include <regex>

std::string test = "abc def abc def";
test = std::regex_replace(test, std::regex("def"), "klm"); // replace 'def' -> 'klm'
// test = "abc klm abc klm"

std::string::replace (C 11 and later)

This member function of the std::string class allows you to replace a substring with a new value. It takes two arguments: the substring to be replaced and the new value.

std::string test = "abc def abc def";
test.replace(test.find("abc"), 3, "hij"); // replace "abc" with "hij"
test.replace(test.find("def"), 3, "klm"); // replace "def" with "klm"
// test = "hij klm hij klm"

The above is the detailed content of How to Replace Substrings in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn