using ONLY the two libraries (#include <string.h>, #include <iostream>), how cou
ID: 3782851 • Letter: U
Question
using ONLY the two libraries (#include <string.h>, #include <iostream>), how could I create a function named trim designed specifically to remove any whitespace from the end of a string? This is my first C++ hw assignment. I'm supposed to use void trim(std::string& s); or something a lot like it as the signature. Secondly, I'm supposed to write a function named "parenthetical" with the following signature std::string parenthetical(const std::string& s); This function will return any text in the given string between an open parenthesis,‘(‘, and a closing parenthesis, ‘)’, returning the empty string if no such test exists. Lastly, I'm supposed to create a main function that creates a few strings to test my functions. Just final details.. Call the trim function with a few of the strings that may or may not need trimming, printing out each string after each call. c. Call the parenthetical function with a few strings, some of which have parentheticals and some of which do not. I'm totally confused and would need a walk through on how this is solved with any commentary you might able to offer. help!!
Explanation / Answer
#include #include std::string trim(const std::string& str, const std::string& whitespace = " ") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " ") { // trim first auto result = trim(str, whitespace); // replace sub ranges auto beginSpace = result.find_first_of(whitespace); while (beginSpace != std::string::npos) { const auto endSpace = result.find_first_not_of(whitespace, beginSpace); const auto range = endSpace - beginSpace; result.replace(beginSpace, range, fill); const auto newStart = beginSpace + fill.length(); beginSpace = result.find_first_of(whitespace, newStart); } return result; } int main(void) { const std::string foo = " too much space "; const std::string bar = "one two"; std::coutRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.