Home > Backend Development > C++ > How Can I Replace Parts of a String in C ?

How Can I Replace Parts of a String in C ?

DDD
Release: 2024-12-22 18:08:11
Original
764 people have browsed it

How Can I Replace Parts of a String in C  ?

Replacing a String Segment with a New String

In C , replacing a part of a string with another string requires a combination of operations. While some libraries offer a dedicated replace() function for direct replacements, here's how you can approach it using standard C functions:

Using find() and replace() Functions

The find() function locates the position of a substring within a string. By combining this with the replace() function, which replaces a specified range with another string, you can effectively replace a part of the string:

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");
Copy after login

This approach replaces the first occurrence of the substring "$name" with "Somename."

Replacing All Occurrences with replaceAll

To replace all occurrences of a substring, you can extend the replace() method to search for and replace multiple instances within the string:

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Adjust start position if 'to' contains 'from'
    }
}
Copy after login

This function performs a successive replacement of all occurrences of the substring "from" with the string "to" within the given string.

The above is the detailed content of How Can I Replace Parts of a String in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template