Dam strings...

Well I've been picking at a program for some time now, and I've come to a obstacle.... I'm looking to have the program take in so many characters. ( mostly sentences), and out the length of the sentence, and what letters or if a space occurs at points 2 4 6 8 10. In the string... So if the sentence is "Hello welcome to Yatatata.... etc". it should print the length being 32 in length. ( using the strlen function) However I can't find a function to print those specific values... ( e, l, , e, c)

Anyone know a function that can do that?
I am a beginner. Could you use strcmp and do something like
1
2
    for (n1 = 0; n1 < [M]; n1++)
        if (strcmp(sentence[n1], ' ') == 0)
or compare the ascii value at that position?
printf("%c", sentence[n1]);

or,... if you are using c++,

cout << sentence[n1] << endl;
I would just write one myself. It seems simple enough.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void outputAtEveryIncrement(string input, int multipleOfThisPosition) {
     for(int i = multipleOfthisPosition - 1; i < input.length() - 1; i += multipleOfThisPosition - 1) {
          cout << input[i]  << ", ";
     }
}

Or

string outputAtEveryIncrement(string input, int multipleOfThisPosition) {
     string iWillReturnThis = "";
     for(int i = multipleOfthisPosition - 1; i < input.length() - 1; i += multipleOfThisPosition - 1) {
          iWillReturnThis +=  input[i]  + ", ";
     }
     return iWillReturnThis;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main ()
{
char* str;
// somehow fill it with a sentence here

// Ouput the length
cout << "Length: " << strlen(str) << "\n";
for (int i=2; i<=10; i+=2)
{
// Output the start of the line
cout << "Element " << i;
if (str[i]==' ') cout << " is a space\n"; // If it is a space
else cout << " is: " << str[i] << "\n"; // Otherwise
}
}
If you wanted to do n multiples of x starting from x, the loop would look like this:
1
2
3
4
5
6
7
for (int i=x; i<=(x*n); i+=x)
{
// Output the start of the line
cout << "Element " << i;
if (str[i]==' ') cout << " is a space\n"; // If it is a space
else cout << " is: " << str[i] << "\n"; // Otherwise
}
Tulock wrote:
and what letters or if a space occurs at points 2 4 6 8 10.


Does this simply mean "what characters occur at..." or does it mean you need to do something different depending on whether or not it's a space?

Based on this quote, "a function to print those specific values... ( e, l, , e, c) " I think it means any character at that position.
1
2
3
4
    char sentence[] = "Hello welcome to Yatatata.... etc";

    for (int i=1; i<strlen(sentence); i+=2)
        cout << '(' << sentence[i] << ")  ";

Output:
(e)  (l)  ( )  (e)  (c)  (m)  ( )  (o)  (Y)  (t)  (t)  (t)  (.)  (.)  ( )  (t)


Topic archived. No new replies allowed.