mercredi 26 août 2015

Deleting substring of your string

I have problem to solve. I must create function that recives 2 parametres, one is string type and other is int. I must input sentence, then one number. My program must delete word that is equal in order to that number. I wrote much of my code, but i have problem, for example if i input number one, or if my sentence contains much blank spaces between words, it does't delete them. I mustn't use iterators. This is my code.

#include <iostream>
#include <string>
#include <algorithm>

int Numberofwords(std::string s)
{
    int trigg (0),suff(0);

    int x(0),y(s.length()-1);

    while(s[x] == ' ')
        x++;

    for(int x(y);x>=0;x--)
    {
        if(s[x]==' ') suff++;
        if(s[x] != ' ') break;
    }

    for(;x<s.length()-suff;x++)
    {
        if(s[x] == ' ') trigg++;
        if((s[x] == s[x+1]) && s[x] == ' ') trigg--;
        if((s[x] == ' ' && s[x+1]==' \n')) trigg--;
    }
    trigg++;
    return trigg;
}

std::string Funkcija(std::string recenica, int n)
{
    int br(Numberofwords(recenica)),x(0),y(recenica.length()-1),suff(0),counter(0),trig(0);

    std::string s;

    if(n<1 || n>br) throw "Inputed number must be bigger than 0 and smaller   then number of words in sentence.";

    while(recenica[x] == ' ')
        x++;

    for(int i(y);i>=0;i--)
    {
        if(recenica[i] == ' ') suff++;
        if(recenica[i] != ' ') break;
    }

    int a(x);
    for(;a<recenica.length()-suff;a++)
    {

        if(recenica[a] == ' ') trig++;

        if(trig == (n-1))
        {
            int e(a);
            while(recenica[e+1] != ' ')
            {
                counter++;
                e++;
            }

            recenica.erase(a+1,counter);
        }

    }
    return recenica;
}

Aucun commentaire:

Enregistrer un commentaire