Finding the longest common suffix between two strings C++ - 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";
}

Related

Is there a way to search an element of a vector<String>, then check if it contains a particular char, if it does print it

The final element in the vector is the char to search for.
Here’s my code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words;
string in;
while(cin>>in)
{
words.push_back(in);
}
int size = words.size()
string check = words.at(size-1);
}
I tried your code and the loop was infinite. Try asking a set number of words then use the find method for each string. Here's an example.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string in;
cout << "Enter 5 words: \n";
for (int i{0}; i < 5; ++i)
{
cout << "Word: ";
cin >> in;
words.push_back(in);
}
cout << "What character do you want to search for? ";
char c;
cin >> c;
for (auto word : words)
{
if (word.find(c) != string::npos)
{
cout << "Character \"" << c << "\" found in " << word << endl;
}
}
return 0;
}
Edit: I noticed that you tried to use int to store the size for the string. Use size_t instead. I also think you meant to use the length method of the string, which also returns size_t.

C++ simple string program

beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}

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;
}

string subscript out of range c++

I need a help in a very basic c++ code.
My program is about guessing name game the problem which i faced is in reading string char by char
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
I don't complete coding...
the problem is in the while loop how can i solve it without using cstring?
could you help me?
int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
Seems like you are trying to print sequence of ? with the length of the string to guess. But you cannot treat std::string as c-string. When its length is n, GuessedName[n] is string subscript out of range - you cannot access one element past end - it's not null-terminated. Use for loop:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
Or simply:
cout << std::string(GuessedName.length(), '?');
Change the while loop like this:
while (GuessedName[i]){
cout<<"?";
i++;
}

c++ find repeated substring within string

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;
}