c++ find repeated substring within string - c++

Im trying to find the number of times a substring repeats within a string input but for some reason when I call the function it gives me a weird number. I have already tested the function within main and it works fine but when I make a standalone function it doesn't work.
Thank you in advance
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int checkHope(string word1)
{
int answer;
int counter;
for(int i = 0; word1[i] != '\0'; i++)
{
answer = word1.find("h", i);
if ((word1.find("o", (answer+1)) == i+1) && (word1.find("e", (answer+3)) == i+3)) counter++;
}
return counter;
}
int main()
{
string word1;
cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
getline(cin, word1);
cout << checkHope(word1);
return 0;
}

//This will work,
//Changes initialize counter to 0, add condition to check alphabet 'p' also in if condition
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int checkHope(string word1)
{
int answer;
int counter=0;
for(int i = 0; word1[i] != '\0'; i++)
{
answer = word1.find("h", i);
if ((word1.find("o", (answer+1)) == i+1)
&& (word1.find("p", (answer+2)) == i+2)
&& (word1.find("e", (answer+3)) == i+3))
counter++;
}
return counter;
}
int main()
{
string word1;
cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
getline(cin, word1);
cout << checkHope(word1);
return 0;
}

Related

Reading String of Varied Sizes // String Manipulation C++

So I just started learning C++ and My professor briefly went over Address (&) and Dereference (*) Operators. I'm not fluent in C++ but i have been searching around for parts and using common knowledge to combine into this code. It fails to build so Please Help!
Assignment- Write a program that keeps reading in strings of varied sizes. If an input string has length greater than one store it in a vector. When an input string has length one (a single character) you will output the string stored in your vector that has the first letter matching the input character. Keep doing this while you read string "quit".
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
char* output;
vector<string> name;
while (input != "quit") {
cin >> input;
if (input.length == 1) {
for (int i = 0; i < name.size; i++) {
output = &name[i].at(0);
if (input == output) {
cout << name[i];
}
}
}
else {
name.push_back(input);
}
}
//system("pause");
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
vector<string> name;
cin >> input;
while (input != "quit") {
if (input.length() == 1) {
for (int i = 0; i < name.size(); i++) {
if (input[0] == name[i][0]) {
cout << name[i] <<endl;
}
}
}
else {
name.push_back(input);
}
cin >> input;
}
system("pause");
return 0;
}

Why is my C++ program only printing one character?

This program is suppose to generate passwords and compare to what the user inputed, if they match it breaks the while loop and outputs the user's input, but for some reason, the generated passwords are just one characters. I am new to C++, I just started like last Friday.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
string Password, Passwords;
cout << "Enter a password: ";
getline(cin, Password);
sleep(.7);
system("clear");
while(Password.compare(Passwords)!= 0)
{
for (int x = 0; x <= Password.length(); x++)
{
for (char Alpha = 'a'; Alpha <= 'z'; Alpha++)
{
if(Alpha == 'z')
{
Alpha = 'a';
}
for(int I=0; I <= 10; I++)
{
Passwords = Alpha + I;
system("clear");
sleep(.7);
cout << Passwords <<endl;
}
}
}
}
cout << "Password found: " << Passwords <<endl;
return 0;
}
After a long back and forward in the comments, the OP explained what was his purpose. To generate random words of the same size as input and stop when it matched the input.
This code does what you want. It's in c++14 so you need a recent compiler and to set the c++14 option. Please note the actual use of random.
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
class RandomCharGenerator {
private:
static std::string s_chars_;
private:
std::random_device rd_{};
std::default_random_engine r_eng_{rd_()};
std::uniform_int_distribution<int> char_dist_{
0, static_cast<int>(s_chars_.size())};
public:
RandomCharGenerator() = default;
auto getRandomChar() -> char { return s_chars_[char_dist_(r_eng_)]; }
auto setRandomString(std::string &str) -> void {
std::generate(std::begin(str), std::end(str),
[this] { return this->getRandomChar(); });
}
};
std::string RandomCharGenerator::s_chars_ = "abcdefghijklmnopqrstuvwxyz";
auto main() -> int {
RandomCharGenerator rand_char;
auto input = std::string{};
cin >> input;
auto generated = std::string(input.size(), ' ');
do {
rand_char.setRandomString(generated);
cout << generated << endl;
} while (input != generated);
cout << "We generated what you input" << endl;
return 0;
}
For input longer than 4 characters it takes a long time to generate the input.
Ideone demo
To understand why you had only 1 char in your Passwords:
Passwords = Alpha + I;
Alpha is a char, I is an int. Their sum is an int. This is converted to char when assigning to Passwords which is a string. So Passwords is now a string composed of only one char.
It's not clear what that actual line of code was supposed to do, so can't tell you what would have been the fix. Maybe you meant to append to Passwords. Then you should have written Passwords += Alpha + I.
The code below is an example of what I am trying to make. I did not make the code below, am just giving you and example of what am trying to do in the code above
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
string password;
string Generated;
cout << "Password to find: ";
cin >> password;
char Alpha[]={'a'-1,'a','a','a','a','a','a','a','a','a'};
while( password.compare(Generated) != 0 )
{
Alpha[0]++;
for(int x=0;x<password.length();x++)
{
if (Alpha[x] == 'z'+1)
{
Alpha[x] = 'a';
Alpha[x + 1]++;
}
}
Generated=Alpha[password.length()-1];
for(int i=password.length()-2; i>=0 ; i-- )
Generated+= Alpha[i];
system("clear");
cout << "Trying: "<< Generated << endl;
}
system("clear");
sleep(1);
cout <<"Access Granted: "<< Generated << endl;
return 0;
}

Need to check if the string is the same when read backwards [duplicate]

This question already has answers here:
to find if a given string is palindrome or is not palindrome
(10 answers)
Closed 8 years ago.
I have no clue what is wrong here. I'm a totally new though.
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <tchar.h>
#include <string>
using namespace std;
int main()
{
int string_length;
string word, wordb;
cout << "Type in a word\n";
cin >> word;
string_length = word.length();
for (int i=1; i < (string_length+1); i++)
wordb = wordb + word.at(i);
if (word == wordb)
cout << "The word is the same in any direction.\n";
else
cout << "The word is not the same in any direction.\n";
return 0;
}
Sorry if it's obvious.
you don't have to "construct" the wordb from word, you can directly compare the letters one by one in one iteration:
for (int i=0; i < string_length; i++) {
if letter_in_pos[i] == letter_in_pos[string_length-i-1]
looks good, do nothing
else
break! word is not a palindrome!
}
and finally, if the word is a real palindrome, you only need to go to the middle of the word (since it's symmetric).
chris suggested the use of std::equal. Here is an example of how that would look like:
#include <string>
#include <algorithm>
#include <iostream>
bool is_palindrome(const std::string& s)
{
return std::equal(s.begin(), s.begin() + s.size()/2, s.rbegin());
}
int main()
{
std::string word;
std::cout << "Type in a word\n";
std::cin >> word;
if (is_palindrome(word))
std::cout << "The word is the same in any direction.\n";
else
std::cout << "The word is not the same in any direction.\n";
}
The simplest way is to write
if ( word == string( word.rbegin(), word.rend() ) )
//...
or
wordb.assign( word.rbegin(), word.rend() );
if ( word == wordb )
//...
As for your approach then the correct loop will look as
for ( string::size_type i = word.length(); i != 0; )
wordb.push_back( word[--i];
or
for ( string::size_type i = word.length(); i != 0; )
wordb += word[--i];
The easiest way I know to do this would be to use the simple logic of A[DeltaX]==B[-DeltaX], While DeltaX <= 1/2 Length. Where A is your first Character, B is your last character, and DeltaX is your step, which should never take you past 1/2 the length of the string (as you will be comparing the first half to the second half).
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <tchar.h>
#include <string>
using namespace std;
int main()
{
int string_length;
int last_character;
bool found_mirror = true;
cout << "Type in a word\n";
cin >> word;
string_length = word.length();
// if the char count is less that 2 than technically it's true
if (string_length < 2)
return true;
last_character = string_length - 1;
for (int i = 0; i <= (string_length / 2); i++)
{
if (word[i] != word[last_character - i])
{
found_mirror = false;
break;
}
}
if (found_mirror)
cout << "The word is the same in any direction.\n";
else
cout << "The word is not the same in any direction.\n";
return 0;
}

Presentation Error:Word Reversal

I have problem with this question I don't know what is wrong with my code that I get Presentation Error every time I don't know what is the format of output can you help me to solve this question I am sorry that my code is a little confusing
here is the link of question http://sharecode.ir/section/problemset/problem/1208
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
string temp=" ";
bool cheak3=false,cheak4=false;
int n,num;
cin>>n;
while(n != 0)
{
if(cheak4 == true)
cout<<endl;
cheak4=true;
cin>>num;
cheak3=false;
string cheak1,cheak;
while(1)
{
if(num ==-1)
break;
getline(cin,temp);
for(int i=0 ; i<temp.size() ; i++)
{
if(temp[i] != ' ')
cheak.push_back(temp[i]);
else
{
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
if(cheak3 == true)
cheak1.push_back(' ');
}
}
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
num--;
if(cheak3 == true)
{
cheak1.push_back(' ');
cout<<cheak1<<endl;
cheak1.clear();
}
cheak3=true;
}
n--;
}
}
I believe the tricky part is you should print a blank line between the output blocks.
Your code has too complicated logic! Here is my solution to this problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, lines;
string word;
cin>>N;
while (N--) {
cin>>lines;
while (lines--) {
char end;
do {
cin >> word;
end = cin.get();
for (int i=word.length()-1;i>=0;i--) cout<<word[i];
cout << end;
} while (end != '\n');
}
if (N) cout << endl;
}
return 0;
}
The line if (N) cout << endl; makes sure you print a newline character for every output block except the last one (when N equals to 0).
After reading each word in a line, you can use cin.get(); in order to determine the next character. If it is a space, then print it and read the next word. Else if it is a \n print it and go to next line! :)

Finding the longest common suffix between two strings C++

I'm fairly new to C++ and I can't seem to figure this out.
I get some weird output when running it. I am also trying to do this in the simplest way possible. How would I go about just printing the word in the suffix array and not all of the extra stuff. I have tried multiple ways to do this and they still show up.
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main(){
char word1[80];
char word2[80];
char suffix[80];
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word1;
int len1 = strlen(word1);
int len2 = strlen(word2);
while(len1 > 0 && len2 > 0 && word1[len1] == word2[len2]) {
int k=0;
suffix[k]=word1[len1];
k++;
len1--;
len2--;
}
for(int i=strlen(suffix);i>=0; i--){
cout << suffix[i];
}
getch();
return 0;
}
Several things:
You should better use string instead of an array of char. That way,
you don't have to worry about memory.
The line int k=0; should be outside of the while.
Remember that arrays start at 0, so substract 1 from the length of
the words and iterate whilelen1 >= 0 && len2 >= 0
Using strings, you can use the method substr (reference
here).
Here is a modified version of your code:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main() {
string word1,word2,suffix;
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word2;
int len1 = word1.size()-1;
int len2 = word2.size()-1;
int k=0;
while(len1 >= 0 && len2 >= 0 && word1[len1] == word2[len2]) {
len1--;
len2--;
k++;
}
suffix=word1.substr(word1.size()-k,k);
cout << suffix;
getch();
return 0;
}
I always think the "simplest way possible" is to use someone else's work. Here
is one way to write your program that leverages the standard library:
#include <algorithm>
#include <string>
#include <iostream>
std::string suffix(const std::string& a, const std::string& b) {
size_t len = std::min(a.size(), b.size());
auto its = std::mismatch(a.rbegin(), a.rbegin()+len, b.rbegin());
return std::string(its.first.base(), a.end());
}
int main () {
std::cout << suffix("December", "May") << "\n";
std::cout << suffix("January", "February") << "\n";
std::cout << suffix("April", "April") << "\n";
}