Print alternate characters

Jan 20, 2008 at 3:43pm
Sample dialog:

Enter a string: HelloWorld
Alternate Character output: ekWrd

I can't figure out how to print alternate characters.
Jan 20, 2008 at 7:36pm
use a for loop to count through the array and modulus to check if the count is even. if so, print the current array element;

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

    // the string is given by the user, so we define a fixed array of char
    // there are other, more refined, ways of doing this, but we'll keep it simple!     
    char my_array[30];
    cout << "enter a string: ";
    cin >> my_array;
    
    // now we get the length of the string in the array (using the length
    // of the array is an obvious mistake to make - it would work up to a
    // point - only we'd print out gibberish once we went past the end
    // of the string).
    int length_of_my_string = strlen(my_array);
    
    // now loop and print out the array element for even values
    // note that we _could_ just increment the loop counter twice for 
    // each loop, but then we'd need to be on our guard against
    // exceeding the end-of-string.
    for (int count=0; count<length_of_my_string; count++)
    {
        // check if count is even, if so print my_array[i]
        if ( count%2 == 0 )                       // "%" is the modulus operator
            cout << my_array[count];
    }

    // and just to show what using the size of the array instead of the     
    // string would do;
    cout << "\n\n";       // don't want output of both loops on the same line!     
    length_of_my_string = sizeof my_array;  // this is where it all goes horribly wrong!      
    for (int count=0; count<length_of_my_string; count++)
    {
        // check if count is even, if so print my_array[i]
        if ( count%2 == 0)                       // "%" is the modulus operator
            cout << my_array[count];
    } 

Last edited on Jan 20, 2008 at 7:48pm
Jan 20, 2008 at 11:36pm
Thanks muzzhogg, problem solved.
Jan 21, 2008 at 1:37pm
A better and faster way to do it would be to use 'count += 2' instead of 'count++', and then you don't need the modulus to check if it's even. This will only loop half as many times, which will be quite a speed increase in large applications with long strings.
Topic archived. No new replies allowed.