I'm trying to write a function that compares two strings, say, s1
and s2
, and if at some position, s1[i] == s2[i]
, then it must increase a counter by one (ie it counts the number of cases which at the same position (say, i
), they contain the same characters).
The code I'm using:
#include <iostream>
#include <string>
using namespace std;
int posicions_iguals(string s1, string s2)
{
int count = 0;
for (int i = 0; i < s1.size(); ++i){
if (s1[i] == s2[i])
++count;
}
return count;
}
int main()
{
string s1;
string s2;
while (cin >> s1) {
cin >> s2;
cout << posicions_iguals(s1, s2) << endl;
}
}
If the size of the first string is greater than the size of the second one (ie s1.size() > s2.size()
), I get the error below:
/usr/include/c++/4.8/bits/basic_string.h:846: std::basic_string<_CharT,
_Traits, _Alloc>::reference std::basic_string<_CharT, _Traits,
_Alloc>::operator[](std::basic_string<_CharT, _Traits, _Alloc>::size_type)
[with _CharT = char; _Traits = std::char_traits<char>; _Alloc =
std::allocator<char>; std::basic_string<_CharT, _Traits,
_Alloc>::reference = char&; std::basic_string<_CharT, _Traits,
_Alloc>::size_type = long unsigned int]: Assertion '__pos <= size()' failed.
Aborted (core dumped)
What should I do now?
Take the bar as length of smaller string:-
int count = 0;
int length = (s1.size() < s2.size()) ? s1.size() : s2.size();
for (int i = 0; i < length; ++i)
{
if (s1[i] == s2[i])
++count;
}
return count;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.