I have two string vectors a and b with a[0]="hello",a[1]="world",b[0]="heyyy"and b[1]="namaste" and i have to decide whether the following a[0] and b[0] has anything matching and a[1] and b[1] has anything matching. If a[0] and b[0] has one or more characters matching then print "YES", else print "NO". Similarly if a[1] and b[1] has one or more characters matching then print "YES", else print "NO". For example from the above information, a[0] and b[0] have 'h' and 'e' as matching and a[1] and b[1] has no character matching. At the end, the expected output is
"YES"
"NO"
Based on the above information, being a beginner in C++ i developed a C++ program which is not even partially correct. It would be great if someone solve this. Thanks in advance.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::vector<string>a,b;
a={"hello", "world"};
b={"heyyy", "namaste"};
const char* acstr;
const char* bcstr;
acstr = a[0].c_str();
bcstr = b[0].c_str();
for(int i=0;i<sizeof(acstr);i++)
{
for(int j=0;j<sizeof(bcstr);j++)
{
if(acstr[i]==bcstr[j])
{
cout << "YES";
}
else{
continue;
}
}
}
return 0;
}
There is no need to convert an object of the type std::string to pointer like
acstr = a[0].c_str();
Also in this loop
for(int i=0;i<sizeof(acstr);i++)
the expression sizeof(acstr) does not give the length of the pointed string. It gives the size of the pointer itself that depending on the used system can be equal to 4 or 8 bytes independent on the length of the pointed string.
In general the vectors can have different number of elements. So you need to use the size of the smallest vector in a loop.
To determine whether a character is present in a string you can use method find of the class std::string.
Here is a demonstrative program.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> v1 = { "hello", "world" };
std::vector<std::string> v2 = { "heyyy", "namaste" };
std::vector<std::string>::size_type n = std::min( v1.size(), v2.size() );
for ( std::vector<std::string>::size_type i = 0; i < n; i++ )
{
std::string::size_type j = 0;
while ( j < v1[i].size() && v2[i].find( v1[i][j] ) == std::string::npos )
{
++j;
}
std::cout << ( j == v1[i].size() ? "NO" : "YES" ) << '\n';
}
return 0;
}
Its output is
YES
NO
Maybe you want like:
#include <bits/stdc++.h> // do not use this header
using namespace std;
int main()
{
std::vector<string>a, b;
a = { "hello", "world" };
b = { "heyyy", "namaste" };
for (int i = 0; i < (int)a.size(); i++)
{
bool bFound = false;
for (int j = 0; j < min(a[i].length(), b[i].length()); j++)
{
if (a[i][j] == b[i][j])
{
bFound = true;
}
}
cout << (bFound ? "YES" : "NO") << endl;
}
return 0;
}
Some advices:
You don't have to use c_str() to do character comparison.
sizeof(const char*) doesn't give you length of string. use strlen(const char*) if you want.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int flag = 0;
std::vector<string>a,b;
a={"hello", "world"};
b={"heyyy", "namaste"};
for(int k=0;k<2;k++){ //You can find and put the length of a or b, instead of using 2
for(int i=0;i<a[k].length();i++)
{
for(int j=0;j<b[k].length();j++)
{
if(a[k][i]==b[k][j])
{
flag = 1;
}
}
}
if(flag == 1){
cout << "YES\n";
}else{
cout << "NO\n";
}
flag = 0;
}
return 0;
}
Related
I am trying to write a program that checks if characters of created word are in different length.
for example word:
PAABBBMMMM
it should print Yes, because P was printed 1 time, A was printed 2 times, B was printed 3 Times, m was printed 4 times.
If the word was for e.g PAABB it should print no, because AA and BB is same length.
What I am doing wrong?
#include <iostream>
using namespace std;
bool checkChars(string s)
{
int n = s.length();
for (int i = 1; i < n; i++)
if (s[i] != s[0])
return false;
return true;
}
// Driver code
int main()
{
string s = "PAABBBMMMM";
if (checkChars(s))
cout << "Yes";
else
cout << "No";
return 0;
}
With the condition if (s[i] != s[0]), you're just checking if each character is equal to the first character, which makes no sense.
You can use a std::map to count the frequency of each character, then use std::set to check the uniqueness of each frequency:
#include <iostream>
#include <string>
#include <map>
#include <set>
bool checkChars(std::string s)
{
int n = s.length(); std::map<int, char> freq;
for (int i = 0; i < n; i++)
freq[s[i]]++;
std::set<int> Unique;
for (auto it = freq.begin(); it!=freq.end(); it++)
Unique.insert(it->second);
if (Unique.size() != freq.size()) {return false;}
return true;
}
// Driver code
int main()
{
std::string s = "PAABBBMMMM";
if (checkChars(s))
std::cout << "Yes";
else
std::cout << "No";
return 0;
}
Result: Yes
Other example:
"AABB" -> No
"MABAAB" -> Yes
Also see Why is "using namespace std;" considered bad practice?
I'm very new to C++. This code is supposed to store and print out every other number and stop when given the symbol #, but the output is weird. It outputs something like 0x6fdd90. Any help would be much appreciated.
#include <iostream>
#include <string>
using namespace std;
int main(){
string s[11];
int count = 1, wordlength = 0;
char a;
cin.get(a);
while (a != '#'){
if (wordlength == 10)
break;
if (count % 2 != 0){
s[wordlength] = a;
wordlength++;
}
cin.get(a);
count++;
}
s[wordlength] = '\0';
cout << s;
return 0;
}
cout << s;
Is printing the address of the 1st element in your array s.
You may want to loop through s to print all the elements.
for (int i =0; i < sizeof(s)/sizeof(s[0]); i++) {
cout<< s[i] << "\n";
}
It is better to user char array than string array for your purpose.
I have to count the vowels of evey word in a given text. My attempt :
#include <iostream>
#include <string.h>
using namespace std;
char s[255], *p, x[50][30];
int c;
int main()
{
cin.get(s, 255);
cin.get();
p = strtok(s, "?.,;");
int n = 0;
while (p)
{
n++;
strcpy(x[n], p);
p = strtok(NULL, "?.,;");
}
for (int i = 1; i <= n; i++)
{
c = 0;
for (int j = 0; j < strlen(x[i]); j++)
if (strchr("aeiouAEIOU", x[i][j]))
c++;
cout << c << " ";
}
return 0;
}
PS: I know that my code is a mix between C and C++, but this is what I am taught in school.
Case closed in the comments.
However, for the fun, I propose you another variant that avoids to use the terrible strtok(), doesn't require a risky strcpy(), and processes each input character only one.
As you are bound to your teacher's mixed style and apparently are not supposed to use c++ strings yet, I also respected this constraint:
const char separators[]=" \t?.,;:"; // I could put them in the code directly
const char vowels[]="aeiouyAEIOUY"; // but it's for easy maintenance
int vowel_count=0, word_count=0;
bool new_word=true;
char *p=s;
cout << "Vowels in each word: ";
do {
if (*p=='\0' || strchr(separators,*p)) {
if (!new_word) { // here, we've reached the end of a word
word_count++;
cout << vowel_count << " ";
vowel_count = 0;
new_word=true;
} // else it's still a new word since consecutive separators
}
else { // here we are processing real chars of a word
new_word=false; // we have at least on char in our word
if (strchr(vowels, *p))
vowel_count++;
}
} while (*p++); // It's a do-while so not to repeat the printing at exit of loop
cout << endl<<"Words: "<<word_count<<endl;
Demo
This is my solution:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char s[255];
int n,i,counter=0;
cin.get(s,255);
for(i=0; i<=strlen(s)-1; i++)
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') counter++;
cout<<counter;
return 0;
}
If you have a vowel( a, e, i, o or u) you are adding up to the counter.
You can also use strchr but this is a more simple, understandable method.
I was trying to create a program in C++ that sorts a given string in alphabetical order in a way where the uppercase letters precede their lowercase equivalent.
Example:
DCBAdcba
Sorted string:
AaBbCcDd
Given below is the code.
#include <iostream>
#include <string>
#include <cctype>
struct char_ {
char c;
char diff;
char_();
char_(char x);
};
char_::char_() {
c = 0;
diff = 0;
}
char_::char_(char x) {
c = std::tolower(x);
diff = c - x;
}
void charswap(char_& x, char_& y) {
char_ temp;
temp = x;
x = y;
y = temp;
}
int main() {
std::string str;
getline(std::cin, str);
char_* str2 = new char_[str.length()];
for (int i = 0; i < str.length(); i++) {
str2[i] = char_(str[i]);
}
/*
for (int i = 0; i < str.length(); i++) {
std::cout << str2[i].c << std::endl;
}
*/
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
if (str2[i].c > str2[j].c)
charswap(str2[i], str2[j]);
}
}
for (int k = 0; k < str.length(); k++) {
std::cout << str2[k].c << "\t" << (int)str2[k].diff << std::endl;
}
for (int i = 0; i < str.length(); i++) {
str2[i].c = str2[i].c - str2[i].diff;
}
for (int i = 0; i < str.length(); i++) std::cout << str2[i].c;
std::cout << "\n";
return 0;
}
A char_ struct is created to store the individual characters(converted to to lowercase) and their difference from the uppercase equivalent(0 or 32, depending if the original char was lowercase or uppercase, respectively). It then sorts the char_ characters on the basis of their lowercase values. And after the sort we add back the difference to the character to retrieve the uppercase form.
But when I try giving this string, it gives the following result.
DCBAdcba
AabBCcdD
I cannot understand what's happening here.
The problem is on this line:
if (str2[i].c > str2[j].c)
charswap(str2[i], str2[j]);
It compares characters in case-insensitive way, with no provision for tie breaking when lowercase characters are the same.
You need to modify this to swap characters when lowercase on the right is greater than lowercase on the left, or when lowercase representations are the same, but the right side original character is in upper case:
if ((str2[i].c > str2[j].c) || (str2[i].c == str2[j].c && str2[j].diff))
charswap(str2[i], str2[j]);
sorts a given string in alphabetical order in a way where the uppercase letters precede their lowercase equivalent.
You can just define a comparison functor reflecting your intention
#include <cctype>
#include <iostream>
#include <vector>
#include <algorithm>
struct case_cmp {
bool operator()(char lhs, char rhs) const {
return (std::isupper(lhs) && std::tolower(lhs) == rhs) || std::tolower(lhs) < std::tolower(rhs);
}
};
Then use std::sort:
int main() {
std::string s("DCBAdcba");
std::sort(std::begin(s), std::end(s), case_cmp());
// Outputs "AaBbCcDd"
std::cout << s << std::endl;
}
std::string can be considered as a container of chars, and as such you can apply STL's algorithms to its content, including std::sort() (just like you would apply an STL algorithm to e.g. std::vector).
You can specify your particular custom sorting criteria using a lambda, to be passed as the third parameter to std::sort(), e.g. (live on Ideone):
#include <algorithm> // for std::sort
#include <cctype> // for std::isupper, std::tolower
#include <iostream> // for std::cout
#include <string> // for std::string
using namespace std;
int main() {
string s{"DCBAdcba"};
sort( s.begin(), s.end(), [](char x, char y) {
// Custom sorting criteria.
// Return true if x precedes y.
// This may work, but requires more testing...
if (isupper(x)) {
if (tolower(x) == y) {
return true;
}
}
return tolower(x) < tolower(y);
});
cout << s << '\n';
}
I am trying to write a program which checks if all the values in an array are equal using a for loop but I cannot figure out a way for the if statement to check if each value in the array are equal other than constantly repeating "if a[i] == a[1] && a[i] == a[0]" and so on. I do not want to do that as i want it to work for any array of any size. Any help is much appreciated!
for (unsigned i = 0; i < val; i++){
if (a[i] == a[0])
return true;
else
return false;
}
for (unsigned i = 0; i < val; i++) {
if (a[i] != a[0]) {
return false;
}
}
return true;
That ought to do it.
In this case, the code will instantly fail on a non-matching value. However, on a matching value it simply continues checking (as we know we need to test EVERY element of the array no matter what). Once that's done, it knows everything went well (since we didn't return early) and returns true.
#include <algorithm>
#include <vector>
#include <iostream>
int main(int argc, char** argv)
{
std::vector<int> eq{ 1, 1, 1, 1 };
std::vector<int> nq{ 1, 2, 1, 1 };
bool eq_res = std::all_of(std::begin(eq), std::end(eq),
[&eq](int c) -> bool
{
return eq[0] == c;
});
bool nq_res = std::all_of(std::begin(nq), std::end(nq),
[&nq](int c) -> bool
{
return nq[0] == c;
});
std::cout << "eq: " << eq_res << std::endl;
std::cout << "nq: " << nq_res << std::endl;
}
Compiled with
g++ --std=c++11 main.cpp
Just for fun, using lambda expression
#include <algorithm>
using namespace std;
template<size_t N>
bool func(int (&arr)[N])
{
int* pOddValue = std::find_if(begin(arr), end(arr),
[&] (int val){ return val != arr[0];});
return pOddValue != end(arr);
}
Using divide and conquer approach, we can reduce the no of comparison to n-1 if n = 2^k like this:
bool divide(int arr[],int size)
{
if( size == 2 ) return arr[0] == arr[1];
if( divide(arr,size/2) && divide(arr+size/2,size/2) )
return arr[0] == arr[size/2];
return false;
}
Another similar way to do it:
for (unsigned i = 1; i < val; i++) {
if (a[i] != a[i-1]) {
return false;
}
}
return true;
It seems that you don't need to handle val = 0.
You can do it in 1 line.
#include <functional>
#include <algorithm>
using namespace std;
return all_of(
a+1, a+val,
bind(equal_to<remove_pointer<decltype(a)>::type>(), a[0], placeholders::_1));