How to remove the leading and trailing commas from a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm>

std::string trimCommas(const std::string& str) {
    size_t start = str.find_first_not_of(',');
    size_t end = str.find_last_not_of(',');
    
    if (start == std::string::npos || end == std::string::npos) {
        return ""; // String contains only commas or is empty
    }
    
    return str.substr(start, end - start + 1);
}

int main() {
    std::string str = ",,,C++,,";
    
    std::cout << "Original: " << str << std::endl;
    
    str = trimCommas(str);

    std::cout << "Trimmed: " << str << std::endl;
}


 
/*
run:
 
Original: ,,,C++,,
Trimmed: C++
 
*/

 



answered Mar 5, 2025 by avibootz
edited Mar 5, 2025 by avibootz

Related questions

1 answer 201 views
3 answers 292 views
2 answers 237 views
1 answer 185 views
3 answers 281 views
2 answers 210 views
...