удалить текст после "." из строки, исключая ".'space '" и последнюю точку в предложении - PullRequest
0 голосов
/ 03 марта 2020

Я хочу удалить 3 символа после полной остановки (.) И хотел бы исключить последнюю полную остановку в моей строке, а также все полные остановки, заканчивающие предложение (определяется как полная остановка + пробел (.)).

Мой код на данный момент удаляет все полные остановки + 3 символа:

string test = "I would .asdlike to.aed remove a.thell these inserts.";

  string target = ".";

  int found=-1;

  do{
    found = test.find(target,found+1);

    if(found!=-1){
      test=test.substr(0,found)+test.substr(found+4);
    }
  }

    while(found != -1);

  cout << test << endl;

К сожалению, я продолжаю получать сообщение об ошибке с окончательным полным остановом в строке, и он удаляет 3 символа, когда Строка включает в себя более одного предложения, разделенных точкой (обозначается как (.)).

Есть мысли?

Ответы [ 2 ]

0 голосов
/ 03 марта 2020

Строковый класс имеет полезную функцию стирания для вас, которую я продемонстрирую здесь:

std::string test = "I would .asdlike to.aed remove a.thell these inserts. And also keep.asd mult.weriple sentences.";

char target = '.';

std::string::iterator stringIter;
for(stringIter = test.begin(); stringIter != test.end(); stringIter++) {
    if (*stringIter == target && stringIter < test.end() - 3 && *(stringIter+1) != ' ') {
        test.erase(stringIter, stringIter+4);
    }
}

std::cout << test << std::endl;

Действительно просто и сравнительно быстро собрать.

И вывод:

I would like to remove all these inserts. And also keep multiple sentences.
0 голосов
/ 03 марта 2020

Я бы сделал так:

#include <string>
#include <iostream>

void solve(std::string &str, char target) {
    std::string s;

    for (int i = 0; i < str.size();) {
        if (str[i] == target) {
            if (i + 4 >= str.size() and str[i] == target) s.push_back(str[i]);
            i += 4;
        } else {
            s.push_back(str[i]);
            i++;
        }
    }
    str = s;
}

int main() {

    std::string test = "I would .asdlike to.aed remove a.thell these inserts.";
    solve(test, '.');

    std::cout << test << std::endl;

    return 0;
}

Выход:

I would like to remove all these inserts.
...