Numbering from 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
#include <cstring>
using namespace std;



int main() {
char s1[10001], s2[10001];
cin >> s1 >> s2;

char *p = strstr(s2, s1);
while (p != 0) {
    cout << p - s2 << " ";
    p = strstr(p + 1, s1);
}
}


Input:
ana
banana

Output: 1 3

But what if I want the numbering to begin at 1? I want to display 2, 4
Just + 1?

cout << p - s2 + 1 << " ";
Hello bstroe,

C++like other languages is zero based, so all the arrays start at zero. If you want the code to output something different then you need to code for that.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char s1[10001], s2[10001];
    
    // <--- Needs a prompt.
    cin >> s1 >> s2;
    
    char *p = strstr(s2, s1);

    while (p != 0) 
    {
        cout << (p - s2) + 1 << " ";

        p = strstr(p + 1, s1);
    }
}


while (p != 0). The zero seems to work, but since "p" is a pointer you really should use "nullptr" especially since "strstr()" returns a null pointer if nothing is found.

Andy
Using c-style string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
	const size_t MAXSTR {1000};
	char s1[MAXSTR] {}, s2[MAXSTR] {};

	cout << "Enter text: ";
	cin.getline(s2, MAXSTR);

	cout << "Enter string to find: ";
	cin.getline(s1, MAXSTR);

	for (char* p {s2}; (p = strstr(p, s1)) != nullptr; cout << (++p - s2) << ' ');
}


Using std::string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1, s2;

	cout << "Enter text: ";
	getline(cin, s2);

	cout << "Enter string to find: ";
	getline(cin, s1);

	for (size_t pos {}; (pos = s2.find(s1, pos)) != string::npos; cout << ++pos << ' ');
}

Last edited on
Topic archived. No new replies allowed.