Почему это дает мне лишние слова? - PullRequest
0 голосов
/ 28 марта 2020

Напишите и протестируйте свою собственную функцию char * funct (char * str, int x), инвертирующую (за исключением символа в позиции n) строку str и возвращающую измененный str в качестве результата. Функцией функции может быть:

Это главное:

  #include <iostream>
  #include <cstring>
  using namespace std;
  char* funct(char *str, int x);
  int main() {

  char str1 [] = "Hello cpp";

  cout << str1 << endl; // Hello cpp

  cout << funct (str, 1) << endl; // pepC ollH // the character at position 1 ('e') stays in place
  return 0;
  }

Это моя функция:

char* funct(char *str, int x) {

int counter = 0;
do {
    counter++;
    str++;
} while (*str);
str--;
char *wskTmp = str;
for (int i = 0; i < counter ; i++) {

    *wskTmp = *str;
    str--;
    wskTmp++;
}
*wskTmp = '\0';
wskTmp = wskTmp - counter;

for (int i = 0; i < counter - x -1; i++) {
    wskTmp++;
}
char tmp;
for (int i = 0; i < counter-3; i++) {
    tmp = *(wskTmp - 1);
    *(wskTmp - 1) = *wskTmp;
    *wskTmp = tmp;
    wskTmp--;
}

return str;
}

Вывод:

Hello Cpp

Hello Cppep C ollH

Должно быть:

Hello Cpp

pep C ollH

Почему он дает мне Hello Cp перед "pep C ollH"?

1 Ответ

2 голосов
/ 28 марта 2020

Ваш код очень запутанный и очень окольный способ решения этой задачи, поэтому я немного реструктурировал его:

#include <cstring>
#include <iostream>
using namespace std;
char *funct(char *str, int x) {
    // keep track of the original start
    char *origStr = str;
    // iterate through the string to find the end
    do {
        str++;
    } while (*str);
    // decrease the string so it's on the last byte, not the nullbyte
    str--;
    // create a start and end
    char *start = origStr;
    char *end = str;
    if (start - origStr == x) {
        start ++;
    }
    if (end - origStr == x) {
        end--;
    }
    // if start >= end then we've finished
    while (start < end) {
        // swap values at start and end
        char temp = *start;
        *start = *end;
        *end = temp;
        // move the pointers closer to each other
        start++;
        end--;
        // skip the index x
        if (start - origStr == x) {
            start++;
        }
        // skip the index x
        if (end - origStr == x) {
            end--;
        }
    }
    // make sure to return the actual start
    return origStr;
}
int main() {
    char str1[] = "Hello cpp";

    cout << str1 << endl;  // Hello cpp

    cout << funct(str1, 1) << endl;  // pepC ollH // the character at position 1
                                     // ('e') stays in place
    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...