Home > Backend Development > C++ > body text

How Can You Split Strings with Multiple Delimiters in C ?

DDD
Release: 2024-11-16 15:58:03
Original
109 people have browsed it

How Can You Split Strings with Multiple Delimiters in C  ?

Splitting Strings with Multiple Delimiters

When tasked with dividing text into meaningful units, developers often encounter the need to separate a string into words. While conventional methods suffice for singular delimiters, what options are available when multiple delimiters are involved?

To address this challenge, a technique employing multiple delimiters for string splitting can be implemented. Let's delve into the solution.

In C , the syntax for parsing a string with a single delimiter using a string stream is as follows:

std::stringstream stringStream(inputString);
std::string word;
while(std::getline(stringStream, word, delimiter)) 
{
    wordVector.push_back(word);
}
Copy after login

To accommodate multiple delimiters, we first read the entire line into a buffer. Subsequently, we iterate over the line, identifying positions where any of the specified delimiters appear. By subtracting the previous position from the current delimiter position, we obtain the substring representing the word and add it to the word vector.

For instance, if we choose space, apostrophe, and semi-colon as delimiters, the following code accomplishes the task:

std::stringstream stringStream(inputString);
std::string line;
while(std::getline(stringStream, line)) 
{
    std::size_t prev = 0, pos;
    while ((pos = line.find_first_of(" ';", prev)) != std::string::npos)
    {
        if (pos > prev)
            wordVector.push_back(line.substr(prev, pos-prev));
        prev = pos+1;
    }
    if (prev < line.length())
        wordVector.push_back(line.substr(prev, std::string::npos));
}
Copy after login

The above is the detailed content of How Can You Split Strings with Multiple Delimiters in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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