+ 1

How can I compare each element of the string with the rest of the string?

For example : string "hello" compare string[0] with the rest ( " ello " ) then string [1] with ( " llo ") I mean comparing one symbol with each symbol of the rest string

28th Apr 2020, 10:31 AM
Eskalate
Eskalate - avatar
7 Answers
+ 4
#include <iostream> #include <string> #include <cctype> #include <cstring> using namespace std; int main() { string word; cin>>word; int len = word.length(); for(int i=0;i<len;i++){ for(int j=i+1;j<len;j++){ if(word[i]==word[j]){ cout<<word[i]<<" at i = "<<i<<" matches with "<<word[j]<<" at j = "<<j<<endl; } } } return 0; }
28th Apr 2020, 10:50 AM
minirkk
minirkk - avatar
+ 2
your attempt? you will need nested for loop for this. the outer loop will deal with "h' and the inner for loop will deal with "ello" and so on.
28th Apr 2020, 10:36 AM
minirkk
minirkk - avatar
+ 2
post your code for better view.
28th Apr 2020, 10:39 AM
minirkk
minirkk - avatar
+ 2
thx for help
28th Apr 2020, 11:06 AM
Eskalate
Eskalate - avatar
+ 1
I had an idea to make a loop with a counter that resets if the character is equal to the character
28th Apr 2020, 10:38 AM
Eskalate
Eskalate - avatar
+ 1
#include <iostream> #include <string> #include <cctype> #include <cstring> using namespace std; int main() { string word; cin>>word; int dejcnt;int elcnt; int len = word.length(); for(int i=0;i<len;i++){ dejcnt += 1; if(word[i]==word[dejcnt]) { dejcnt = 0; elcnt += 1;//counter of comparings; } } return 0; }
28th Apr 2020, 10:44 AM
Eskalate
Eskalate - avatar
+ 1
so this cycle seeking match . its make 1 step if he founded a match , only 'j' make multiple-steps?
28th Apr 2020, 11:11 AM
Eskalate
Eskalate - avatar