How to delete a character from each word in the sentence

i was trying to do a program that ask you how many characters you wish to delete from each word
as example:
you enter the sentence : HI HOW ARE YOU
delimiter(strtok): space
number of characters to delete from each word: 1

the sentence becomes : I OW RE OU

#include <iostream.h>
#include <cstring>
char *mytok(char *,char *,int );
main(){
char s1[40];
char s2[40];
int n;
cout<<"Write down your sentence"<<endl;
cin.getline(s1,40,'\n');
cout<<"Enter your token or delimiter, -i assure you can enter more than one-"<<endl;
cin.getline(s2,40,'\n');
cout<<"How many characters you wish to delete from each word ? "<<endl;
cin>>n;
mytok(s1,s2,n);
}
char *mytok(char * s1,char * s2,int x){
int c;
char *sentence = new char[50];
sentence = strtok(s1,s2);
char *re = new char[40];
while(sentence != NULL){
c=0;
while (c<=x){
c++;
sentence++;
}
while(*sentence != '\0'){
*re = *sentence;
sentence++;
re++;
}
sentence++;
}
cout<<re<<endl;
}
Edit & Run
Last edited on
If c-style strings with std::strtok() must be used, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <cstring>

int main()
{
    char sentence[1024] {} ;
    std::cout << "Write down your sentence. max(" << sizeof(sentence) - 1 << " characters)\n" ;
    std::cin.getline( sentence, sizeof(sentence) ) ;
    if( std::cin.fail() )
    {
        std::cout << "too many characters!\n" ;
        return 1 ;
    }

    const auto end_pos = std::cin.gcount() - 1 ; // position of the last character

    char delimiters[32] {} ;
    std::cout << "Enter your delimiters  max(" << sizeof(delimiters) - 1
              << " characters), I assure you can enter more than one\n" ;
    std::cin.getline( delimiters, sizeof(delimiters) ) ;
    if( std::cin.fail() || std::cin.gcount() < 2 )
    {
        std::cout << "no delimiters were entered!\n" ;
        return 1 ;
    }

    int nchars ;
    std::cout << "How many characters you wish to delete from each word? " ;
    std::cin >> nchars ;

    for( char* word = std::strtok( sentence, delimiters ) ;
         word != nullptr ;
         word = std::strtok( nullptr, delimiters ) ) // for each word in the sentence
    {
        // make the first nchars characters of this word a delimiter
        for( int i = 0 ; i < nchars && word[i] ; ++i ) word[i] = delimiters[0] ;
    }

    // convert all null characters put in by strtok to the first delimiter
    for( int i = 0 ; i < end_pos ; ++i ) if( sentence[i] == 0 ) sentence[i] = delimiters[0] ;

    for( char* word = std::strtok( sentence, delimiters ) ;
         word != nullptr ;
         word = std::strtok( nullptr, delimiters ) ) // for each word in the sentence
    {
        std::cout << word << ' ' ; // print it out followed by a space
    }
    std::cout << '\n' ;
}
Topic archived. No new replies allowed.