Task: Offer two variants of the function that removes leading and trailing spaces from a string. Help, please, repair the program code: Does not display the converted string, tell me what is wrong?

void FirstRemoveSpaces(char str[]) { int i, j; int len = strlen(str); // определяем количество символов for (i = 0, j = 0; str[i]; ++i) if (str[0] != ' ' || str[len - 1] != ' ') { // если не нашли пробел str[j++] = str[i]; // записываем в строку символ } str[j] = 0; cout << "Строка преобразована первым способом: "; puts(str); // вывод строки } 

And with the error in the second function, I can not understand what is wrong? void SecondRemoveSpaces (string s) {

  if (s[0] == ' ') { s.erase(0, 1); // удаление символа } int len = s.length - 1; if (s[len] == ' ') { s.erase(len, 1); // удаление символа } } 

Well, the full program:

 #include "pch.h" #include <iostream> using namespace std; void FirstRemoveSpaces(char str[]) { int i, j; int len = strlen(str); // определяем количество символов for (i = 0, j = 0; str[i]; ++i) if (str[0] != ' ' || str[len - 1] != ' ') { // если не нашли пробел str[j++] = str[i]; // записываем в строку символ } str[j] = 0; cout << "Строка преобразована первым способом: "; puts(str); // вывод строки } void SecondRemoveSpaces(string s) { if (s[0] == ' ') // если встречается больше двух пробелов подряд { s.erase(0, 1); // удаление символа } int len = s.length - 1; if (s[len] == ' ') // если встречается больше двух пробелов подряд { s.erase(len, 1); // удаление символа } } int main() { setlocale(LC_ALL, "Russian"); // подключение русского языка char str[] = " Hi, this is a test! "; // инциализация строки string s = str; cout << "Строка: " << str << endl; // вывод строки FirstRemoveSpaces(str); // вызов первой функции SecondRemoveSpaces(s); } 
  • 1. SecondRemoveSpaces(string &s) forgot the ampersand. 2. int len = s.length() - 1; length () is a function. - uber42 3:14 pm
  • Well, if there are a lot of gaps? ... - AR Hovsepyan

1 answer 1

Let's start with the second function. First, since you wrote:

 void SecondRemoveSpaces(string s)... 

This already means that all your actions will occur with a copy of the string object, and not with the object itself. Therefore, your object on any will not change its value. Correctly transfer the reference to the object ... Secondly, you did not take into account that there may be more than one gap. There are many ways. I will present one:

 void SecondRemoveSpaces(string& s) { size_t first = s.find_first_not_of(' '), last = s.find_last_not_of(' '); s = (first != string::npos) ? s.substr(first, last - first + 1) : ""; } 

But it is more convenient if such functions return a result. Therefore, the option is still better:

 string& SecondRemoveSpaces(string& s) { size_t first = s.find_first_not_of(' '), last = s.find_last_not_of(' '); s = (first != string::npos) ? s.substr(first, last - first + 1 ) : ""; return s; } 

So that in the program we could immediately carry out the assignment or, for example, output:

 cout << SecondRemoveSpaces(s); 

With the first function, things are different. Considering that arrays are passed by reference, then everything is correct by syntax, but in the logic of the function there are errors that are better explained by the correct code so as not to be wordy ...

 void FirstRemoveSpaces(char str[]) { size_t i = 0, len = strlen(str); // количество символов while(str[--len] == ' '); while (str[i++] == ' '); if (i == 1) //не было пробелов str[++len] = '\0'; else { --i; // это количество начальных пробелов size_t j = 0; while (j <= len - i) { str[j] = str[j + i]; // сдвигаем все влево на i ++j; } str[j] = '\0'; } } 

Another option without checking the conditions:

 string& RemoveSpaces(string& s) { s.erase(0, s.find_first_not_of(' ')); auto f = [](char c) { return c != ' '; }; s.erase((std::find_if(s.rbegin(), s.rend(), f)).base(), s.end()); return s; } 
  • Well, with the first function, you have generally serious logical errors - AR Hovsepyan
  • C substr little bit wrong, her second parameter is length. Something like s = (first != last ? s.substr(first, last-first+1) : ""); . (A check for equality resolves the situation when there are only spaces in the string.) - HolyBlackCat
  • Apparently, just the same with the first argument. "You can just test ..." And I tested. Option s = s.substr(first, last); gives an incorrect result (does not cut some of the spaces at the end of the line) If there is nothing in the line except spaces, this option will crash at all. And s = (first != last ? s.substr(first, last-first+1) : ""); works fine in both cases. - HolyBlackCat
  • @HolyBlackCat, yes, you are right, I just forgot to add a check. Of course in such cases firs == string :: npos .... Thank you - AR Hovsepyan 6:13 pm
  • one
    @HolyBlackCat, I once again read about the method, you are right. I remembered and tested incorrectly ... I got confused of course: old age is not a joy .. - AR Hovsepyan