How to compare a certain character with another character of a string - c++

In the following code, I am having trouble comparing specific letters two given strings.
#include <bits/stdc++.h>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
cin.ignore();
string phrases[m];
string records[n];
for (int i = 0; i < m; i++) {
getline(cin, phrases[i]);
}
for (int i = 0; i < n; i++) {
getline(cin, records[i]);
}
int lowBound;
sort(phrases, phrases + m);
int ans = 0;
bool stillIs;
for (int i = 0; i < n; i++) {
lowBound = lower_bound(phrases, phrases + m, records[i]) - phrases;
if (lowBound == m) {
continue;
}
stillIs = true;
for (int j = 0; j < records[i].length(); i++) {
if (records[i][j] == phrases[lowBound][j]) {
stillIs = false;
}
}
if (stillIs) {
ans++;
}
}
cout << ans;
return 0;
}
On line 33, if (records[i][j] == phrases[lowBound][j]), it is not giving me an error, but if I run it with this line, nothing happens, but when I comment the if statement out, it works properly, but obviously not giving me the correct answer. Is there any way I can compare these two strings (the second one is larger in size than the first one) to find whether the first one is the start of the second one?
Thanks!

You are incrementing i instead of j in the loop at line 32
You have your test backwards in line 33 - you want to set stillIs = false if the characters don't match, (i.e., !=)
I haven't fully read your code, but those two problems jumped out at me, so see if that sorts it out

Related

C++, Find out if a string contains a substring?

I don't know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help
#include <iostream>
#include <string>
using namespace std;
string Words, Sentence, buf;
int i, n, j = 0;
string arr[20];
bool A;
int main() {
cout << "Words separated by slashes";
cin >> Words;
cout << "Sentence";
cin >> Sentence;
for (i = 0; i <= Words.length(); i++)
{
if (Words[i] != '/')
{
buf = buf + Words[i];
}
else
{
arr[n] = buf;
n = n + 1;
buf = "";
}
}
for (j = 0; j <= n; j++)
{
cout << arr[j] << "\n";
if (Sentence.find(arr[j]) != string::npos)
{
A = true;
}
}
if (A == true)
{
cout << "Contains.";
}
else
{
enter code herecout << "Does not contain.";
}
}
There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one.
for (i = 0; i <= Words.length(); i++)
and
for (j = 0; j <= n; j++)
should be
for (i = 0; i < Words.length(); i++)
and
for (j = 0; j < n; j++)
The valid indexes for a string, vector or array are zero upto but not including the size of the string, vector or array.
This mistake causes the bug that you see. Suppose you have two words in arr, e.g. arr = { "stack", "overflow", "", "", ... } . Because you go around the for loop one too many times you end up searching for arr[2] which equals "". This search always succeeds because every string contains the empty string. And so you always set A to true.

Why some compiler shows unfavorable output for a specific input?

Look at this code, In my VS code or some online compilers it gives favorable output, but when I'm submitting this on HackerRank or this online compiler I'm getting wrong output but only when I provide input as: 1 1 1 100...and I'm not able to spot the Error?..I'm providing question for reference.
/*There will be two arrays of integers. Determine all integers that satisfy
the following two conditions:
The elements of the first array are all factors of the integer being
considered
The integer being considered is a factor of all elements of the second array
These numbers are referred to as being between the two arrays. Determine how
many such numbers exist.
*/
#include <iostream>
int main()
{
int count1, count2;
int num1[20], num2[20];
std::cin >> count1 >> count2;
for (int i = 0; i < count1; i++)
{
std::cin >> num1[i];
}
for (int i = 0; i < count2; i++)
{
std::cin >> num2[i];
}
int occurence_firstarray = 0, occurence_secondarray = 0, totalvalid_occurence = 0;
for (int i = num1[count1 - 1]; i < num2[1]; i++)
{
occurence_firstarray = 0;
occurence_secondarray = 0;
for (int j = 0; j < count1; j++)
{
if (i % num1[j] == 0)
{
occurence_firstarray++;
}
}
if (occurence_firstarray == count1)
{
for (int p = 0; p < count2; p++)
{
if (num2[p] % i == 0)
{
occurence_secondarray++;
}
}
}
if (occurence_secondarray == count2)
{
totalvalid_occurence++;
}
}
std::cout << totalvalid_occurence;
return (0);
}
Considering your inputs: 1 1 1 100,
What are you doing in this code is You are pointing on index beyond your second array's size limit i < num2[1], this is why you are getting wrong outputs.
Do some changes as, i <= num2[0];

what changes should i have to do to in my cpp code to get correct output?

//Question
/*There are N seats in a row. You are given a string S with length N; for each valid i, the i-th character of S is '0' if the i-th seat is empty or '1' if there is someone sitting in that seat.
Two people are friends if they are sitting next to each other. Two friends are always part of the same group of friends. Can you find the total number of groups?
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S.
Output
For each test case, print a single line containing one integer ― the number of groups.*/
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin>>t;
int n=1e6;
for(int i=0;i<t;i++){
string g1;
cin>>g1;
int group;
group = 0;
for(int j=0;j<g1.length();j++){
if(g1[j] == '1'){
for(int h=1;h<n;h++){
if(g1[j+h] == '1'){
h++;
}else{
break;
}
group++;
}
} else{
continue;
}
}
cout<<group<<endl;
}
return 0;}
Example Input
4
000
010
101
01011011011110
Example Output
0
1
2
4
//my output
0
0
0
9
Based on sample output, you suppose to count '1's between zeros, which is the number of groups you have. Here is your implementation with small correction to do that.
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// int n = 1e6; --> not used
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group;
group = 0;
for (size_t j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++;
//skip all '1' before the first '0'
while (g1[j] == '1' && j < g1.length())
j++;
}
else {
continue;
}
}
cout << group << endl;
}
return 0;
}
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// you don't need n variable
// it is appropriate to use the length of the string instead
// it also will remove one warning for initialization
int n = 1e6;
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group; // you can use int group = 0; avoiding the statement below
group = 0;
// size_t stringLength = g1.length();
for (int j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++; // you need to add it here to starts counting
// better this way -> for (size_t h = 1; h < stringLength; h++)
for (int h = 1; h < n; h++) { // h < n && (j+h)<stringLength
if (g1[j + h] == '1') {
// you increasing h value twice - first in for statement, second here
// instead, you need to set j to j+h value
//h++;
// you just "moving" through the string till next'0'
j = j + h;
}
else {
break;
}
// this will increase group count for each next '1' in the string
// this is why you got 9 for the last string in your's example
//group++;
}
}
// this is not needed
//else {
// continue;
//}
}
cout << group << endl;
}
return 0;
}

sum of digits at odd and even places of a string

The output for the variable sum_e is negative which isn't what I expect it to be.
I have simply added the values at even and odd places and stored them in two variables. I checked for solutions and found ones with digit extraction from a number. None of them had a string input.
#include<iostream>
using namespace std;
int main(){
string s;
cin>>s;
int sum_e=0,sum_o=0;
int l=s.length();
for(int i=0;i<=l;i=i+2){
sum_o+=(s[i]-'0');
}
for(int j=1;j<=l;j=j+2){
sum_e+=(s[j]-'0');
}
cout<<sum_o<<endl<<sum_e;
return 0;
}
I subtracted '0' from the string index to convert it into int. One of the variables shows the right output and the other shows a negative one.
Your for loops run one time longer than the length of the array, so when i = l, s[i] will get an undefined/garbage value from memory. Use i < l and j < l rather than i <= l and j <= l, since the index in C++ begins at zero.
#include <iostream>
using namespace std;
int main(){
string s;
cin >> s;
int sum_e = 0, sum_o = 0;
int l = s.length();
for(int i = 0; i < l; i = i + 2){
sum_o += (s[i] - '0');
}
for(int j = 1; j < l; j = j + 2){
sum_e += (s[j] - '0');
}
cout << sum_o << endl << sum_e;
return 0;
}
To improve your code, use one for loop instead of two.
for(int i = 0; i < l; i++){
// Check if even (i%2 returns the remainder of i/2, so here i%2==1 means even)
if(i%2 == 1){
sum_e += (s[i] - '0');
}else{
sum_o += (s[i] - '0');
}
}
Array indexing in C++ starts from 0. You store the length of string as l, so elements of your string lies from s[0] to s[l-1]. At s[l] some garbage value is present which gets added to one of your variables, hence producing undesired results.
#include<iostream>
using namespace std;
int main(){
string s;
cin>>s;
int sum_e=0,sum_o=0;
int l=s.length();
for(int i=0;i<l;i=i+2){ // use <
sum_o+=(s[i]-'0');
}
for(int j=1;j<l;j=j+2){ // use <
sum_e+=(s[j]-'0');
}
cout<<sum_o<<endl<<sum_e;
return 0;
}
You can also do your odd and even position sum using a single loop. Your code size will reduce and look better
for(int i=0;i<l;i=i+2){
if(i%2==0)// even index means odd position numbers
sum_o+=(s[i]-'0');
else
sum_e+=(s[j]-'0');
}

Error reading string with cin

I have a silly mistake , but managed not find it is. On line 17 I try to read two integers and a string, but when I input (or similar):
2 3 (
I keep being asked entries. When I input (or similar):
2 3 F
reads smoothly. Could it be " ( " a special character ?
#include <iostream>
using namespace std;
int ocurs(string cad, string subcad) {
int con = -1;
size_t i = 0;
while(i != string::npos) {
i = cad.find(subcad, i);
con++;
}
return con;
}
int main() {
int n, m, con = 0;
string cad, subcad;
cin >> n >> m >> subcad;
//cout << subcad;
for(int i = 0; i < n / 2; i++)
cad.push_back('(');
for(int i = 0; i < n / 2; i++)
cad.push_back(')');
//cout << cad;
con += ocurs(cad, subcad);
cad.clear();
for(int i = 0; i < n; i++)
if(i % 2 == 0) cad.push_back('(');
else cad.push_back(')');
con += ocurs(cad, subcad);
cout << con;
return 0;
}
You end up in an endless loop inside ocurs(), because when cad.find() finds the sought substring, you feed it with the same index it returns, and it keeps finding the same substring. You need to fix your ocurs() routine, for example by adding
if (i != string::npos) ++i;
after the find statement.
The broader answer is that you should learn to use a debugger – or, at least, use some more cout statements where they might be useful.