I am trying to write a code in c++ that take string input from user and arrange the string in alphabetical order. Now I want to extend this code to give me output like how many times 'a' appears and so on, but I could not extend it. There may be many ways to deal with this problem, but please if anyone can guide me how to deal with this problem using arrays.
#include <iostream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
int main()
{
cout << " please enter your charactor " << endl;
string ch;
getline(cin, ch);
int i, step, temp;
for (step = 0; step<ch.size() - 1; ++step)
for (i = 0; i<ch.size()- step - 1; ++i)
{
tolower(ch[1]);
if (tolower(ch[i])>tolower(ch[i + 1]))
{
temp = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = temp;
}
}
// count the appearance of each letter using array
cout << " total lenght of your string's charactor is " << ch.length() << endl;
system("pause");
}
This is all you need
#include <iostream>
#include <string>
using namespace std;
int main()
{
// you could easily use a vector instead of an array here if you want.
int counter[26]={0};
string my_string = "some letters";
for(char c : my_string) {
if (isalpha(c)) {
counter[tolower(c)-'a']++;
}
}
// thanks to #James
for (int i = 0; i < 26; i++)
{
cout << char('a' + i) << ": " << counter[i] << endl;
}
}
subtracting 'a' from a character baselines the letter 'a' to position 0 in the array. You can add the letter 'a' back to the position when printing it back out.
Using the range-based for loop requires c++11, but you can use a traditional for loop instead in the same way.
Technically this only works for languages with 26 or fewer letters in their alphabet...
Related
I need to find and print common characters in different strings. My code does not work as it should, it checks for same letters at the same index but thats not what I want. I couldn't find better solution for now. Thank you for help :)
#include <iostream>
#include <string>
using namespace std;
int main() {
string niz1, niz2, niz3 = "";
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
for (int i = 0; i < niz1.length() - 1; i++) {
for (int j = 0; j < niz2.length() - 1; j++) {
if (niz1[i] == niz2[j])
niz3 += niz1[i];
}
}
cout << "Same letters are: " << niz3 << endl;
return 0;
}
Below is corrected working code. Basically the only correction that was needed to do is to make both loops have upper bound of niz.length() instead of niz.length() - 1.
Variant 1:
Try it online!
#include <string>
#include <iostream>
using namespace std;
int main() {
string niz1, niz2, niz3 = "";
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
for (int i = 0; i < niz1.length(); i++) {
for (int j = 0; j < niz2.length(); j++) {
if (niz1[i] == niz2[j])
niz3 += niz1[i];
}
}
cout << "Same letters are: " << niz3 << endl;
return 0;
}
Input:
string 1: adbc
string 2: cde
Output:
Same letters are: dc
Also you may want to sort letters and make them unique, then you need to use std::set too like in code below:
Variant 2:
Try it online!
#include <string>
#include <iostream>
#include <set>
using namespace std;
int main() {
string niz1, niz2, niz3 = "";
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
for (int i = 0; i < niz1.length(); i++) {
for (int j = 0; j < niz2.length(); j++) {
if (niz1[i] == niz2[j])
niz3 += niz1[i];
}
}
set<char> unique(niz3.begin(), niz3.end());
niz3.assign(unique.begin(), unique.end());
cout << "Same letters are: " << niz3 << endl;
return 0;
}
Input:
string 1: adbcda
string 2: cdecd
Output:
Same letters are: cd
Also you may use just sets plus set_intersection standard function. This will solve your task in less time, in O(N*log(N)) time instead of your O(N^2) time.
Variant 3:
Try it online!
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
string niz1, niz2, niz3 = "";
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
set<char> s1(niz1.begin(), niz1.end()), s2(niz2.begin(), niz2.end());
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(niz3));
cout << "Same letters are: " << niz3 << endl;
return 0;
}
Input:
string 1: adbcda
string 2: cdecd
Output:
Same letters are: cd
Instead of set it is also possible to use unordered_set, it will give even more faster algorithm especially for long strings, algorithm will have running time O(N) compared to O(N * log(N)) for set solution. The only drawback is that unlike for set solution output of unordered_set solution is unsorted (but unique) (unordered sets don't sort their data).
Variant 4:
Try it online!
#include <string>
#include <iostream>
#include <unordered_set>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
string niz1, niz2, niz3;
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
unordered_set<char> s1(niz1.begin(), niz1.end()), s2;
for (size_t i = 0; i < niz2.length(); ++i)
if (s1.count(niz2[i]))
s2.insert(niz2[i]);
niz3.assign(s2.begin(), s2.end());
cout << "Same letters are: " << niz3 << endl;
return 0;
}
Input:
string 1: adbcda
string 2: cdecd
Output:
Same letters are: dc
Also one more way is to use just plain for loops like you did, without sets, but do extra block of loops in order to remove non-unique letters, like in code below. The only drawbacks of this loops method compared to sets method is that loops method runs slower and produces non-sorted output string.
Variant 5:
Try it online!
#include <string>
#include <iostream>
using namespace std;
int main() {
string niz1, niz2, niz3, niz4;
cout << "string 1: ";
getline(cin, niz1);
cout << "string 2: ";
getline(cin, niz2);
for (int i = 0; i < niz1.length(); ++i)
for (int j = 0; j < niz2.length(); ++j)
if (niz1[i] == niz2[j])
niz3 += niz1[i];
for (int i = 0; i < niz3.length(); ++i) {
bool exists = false;
for (int j = 0; j < niz4.length(); ++j)
if (niz4[j] == niz3[i]) {
exists = true;
break;
}
if (!exists)
niz4 += niz3[i];
}
cout << "Same letters are: " << niz4 << endl;
return 0;
}
Input:
string 1: adbcda
string 2: cdecd
Output:
Same letters are: dc
This is sort of an answer in itself, and sort of an extended comment on #Arty's answer.
Hash tables (which are what underlies an unordered_map) are really useful under many circumstances. But in this case, they're kind of overkill. In particular, a hash table is basically a way of creating a sparse array for cases where it's unrealistic or unreasonable to use the underlying "key" type directly as an index into an array.
In this case, however, what we're using as the key in the hash table is a character--a single byte. This is small enough, it's utterly trivial to just use an array, and use the byte directly as an index into the array.
So, with arrays instead of hash tables, we get code something on this order:
#include <array>
#include <string>
#include <iostream>
#include <chrono>
std::string getstring(std::string const &s) {
std::cout << s << ": ";
std::string input;
std::getline(std::cin, input);
return input;
}
using namespace std::chrono;
int main() {
std::array<char, 256> a = {0};
std::array<char, 256> b = {0};
std::array<char, 256> result = { 0 };
std::size_t pos=0;
std::string s1 = getstring("s1");
std::string s2 = getstring("s2");
std::cout << "s1: " << s1 << "\n";
std::cout << "s2: " << s2 << "\n";
auto start = high_resolution_clock::now();
for (auto c : s1)
a[c] = 1;
for (auto c : s2)
b[c] = 1;
for (int i = 'a'; i < 'z'; i++)
if (a[i] != 0 && b[i] != 0)
result[pos++] = i;
for (int i = 'A'; i < 'Z'; i++)
if (a[i] != 0 && b[i] != 0)
result[pos++] = i;
auto stop = high_resolution_clock::now();
std::cout << "Common characters: " << std::string(result.data(), pos) <<"\n";
std::cout << "Time: " << duration_cast<nanoseconds>(stop - start).count() << " nS\n ";
}
To get some repeatable test conditions, I built an input file with a couple of long fairly strings:
asdffghjllkjpoiuwqertqwerxvzxvcn
qqweroiglkgfpoilkagfskeqwriougfkljzxbvckxzv
After adding instrumentation (timing code) to his Variant 4 code, I found that his code ran in about 12,000 to 12,500 nanoseconds.
The code above, on the other hand, runs (on the same hardware) in about 850 nanoseconds, or around 15 times as fast.
I'm going to go on record as saying the opposite: although this is clearly faster, I'm pretty sure it's not the fastest possible. I can see at least one fairly obvious improvement (store only one bit per character instead of one byte) that would probably improve speed by at least 2x, and could theoretically yield an improvement around 8x or so. Unfortunately, we've already sped other things up enough that I doubt we'd see 8x--we'd probably see a bottleneck on reading in the data from memory first (but it's hard to be sure, and likely to vary between processors). So, I'm going to leave that alone, at least for now. For now, I'll settle for only about fifteen times faster than "the fastest possible solution"... :-)
I suppose, in fairness, he probably really meant asymptotically the fastest. His has (expected, but not guaranteed) O(N) complexity, and mine also has O(N) complexity (but in this case, basically guaranteed, not not just expected. In other words, the 15x is roughly a constant factor, not one we expect to change significantly with the size of the input string. Nonetheless, even if it's "only" a constant factor, 15x is still a pretty noticeable difference in speed.
I need to write a function that gets a string and count how many words there are in the string and how many letters. And then calculate the average of it.
A word in a string is a sequence of letters and numbers separated by one or more spaces.
First of all I have to check if the string is correct. The string must contain only lowercase letters, uppercase letters, and numbers only.
i didnt menage to count all sort of words correctly and also my function doesnt count the last letter.
#include <iostream>
using namespace std;
#include <string.h>
#define SIZE 50
float checkString(char string[]) {
float wordCounter = 0;
float letterCounter = 0;
bool isLegit = true;
int i = 0;
while (isLegit) {
if (((string[i] >= 48 && string[i] <= 57) ||
(string[i] >= 65 && string[i] <= 90) ||
(string[i] >= 97 && string[i] <= 122 ))) {
for (int j = 0; j <= strlen(string); j++) {
if ((string[j - 1] != ' ' && string[j] == ' ' &&
string[i + 1] != ' ')
|| j == (strlen(string) - 1)) {
wordCounter++;
}
else if (string[j] != ' ') {
letterCounter++;
cout << string[j];
}
}
cout << " The avareage is : " << (letterCounter /
wordCounter) << endl;
isLegit = false;
}
else {
return -1;
isLegit = false;
}
}
cout << "Number of words " << wordCounter << endl;
cout << "Number of letters " <<letterCounter << endl;
}
int main() {
char string[SIZE];
cout << "please enter a sentence " << endl;
cin.getline(string, SIZE);
checkString(string);
}
Instead of using char[] for strings, I suggest that you use std::string which can grow and shrink dynamically. It's one of the most common types to use in the standard C++ library. You can also make use of stringstreams which lets you put a string inside it and then you can extract the contents of the stringstream using >>, just like when reading from std::cin.
Example with comments in the code:
#include <iostream>
#include <sstream> // std::stringstream
#include <string> // std::string
// use std::string instead of a char[]
float checkString(const std::string& string) {
// put the string in a stringstream to extract word-by-word
std::istringstream is(string);
unsigned words = 0;
unsigned letters = 0;
std::string word;
// extract one word at a time from the stringstream:
while(is >> word) {
// erase invalid characters:
for(auto it = word.begin(); it != word.end();) {
// Don't use magic numbers. Put the character literals in the code so
// everyone can see what you mean
if((*it>='0' && *it<='9')||(*it>='A' && *it<='Z')||(*it>='a' && *it<='z')) {
// it was a valid char
++it;
} else {
// it was an invalid char, erase it
it = word.erase(it);
}
}
// if the word still has some characters in it, make it count:
if(word.size()) {
++words;
letters += word.size();
std::cout << '\'' << word << "'\n"; // for debugging
}
}
std::cout << "Number of words " << words << "\n";
std::cout << "Number of letters " << letters << "\n";
std::cout << "The average number of letters per word is "
<< static_cast<float>(letters) / words << '\n';
return 0.f; // not sure what you are supposed to return, but since the function
// signature says that you should return a float, you must return a float.
}
int main() {
checkString(" Hello !!! World, now let's see if it works. ");
}
I would like to add an additional answer. This answer is based on "more-modern" C++ and the usage of algorithms. You want to solve 3 tasks:
Check, if string is OK and matched to your expectations
Count the number of words in the given string
Count the number of letters
Calculate the ratio of words/letters
For all this you may use existings algorithms from the C++ standard library. In the attached example code, you will see a one-liner for each task.
The statements are somehow very simple, so that I will not explain much more. If there should be a question, I am happy to answer.
Please see here one possible example code:
#include <iostream>
#include <string>
#include <iterator>
#include <regex>
#include <algorithm>
#include <tuple>
#include <cctype>
std::regex re("\\w+");
std::tuple<bool, int, int, double> checkString(const std::string& str) {
// Check if string consists only of allowed values, spaces or alpha numerical
bool stringOK{ std::all_of(str.begin(), str.end(), [](const char c) { return std::isalnum(c) || std::isspace(c); }) };
// Count the number of words
int numberOfWords{ std::distance(std::sregex_token_iterator(str.begin(),str.end(), re, 1), {}) };
// Count the number of letters
int numberOfLetters{ std::count_if(str.begin(), str.end(), isalnum) };
// Return all calculated values
return std::make_tuple(stringOK, numberOfWords, numberOfLetters, static_cast<double>(numberOfWords)/ numberOfLetters);
}
int main() {
// Ask user to input string
std::cout << "Please enter a sentence:\n";
// Get string from user
if (std::string str{}; std::getline(std::cin, str)) {
// Analyze string
auto [stringOk, numberOfWords, numberOfLetters, ratio] = checkString(str);
// SHow result
std::cout << "\nString content check: " << (stringOk ? "OK" : "NOK") << "\nNumber of words: "
<< numberOfWords << "\nNumber of letters: " << numberOfLetters << "\nRatio: " << ratio << "\n";
}
return 0;
}
Of course there are many more other possible solutions. But, because of the simplicity of this solution, I showed this variant.
As a homework exercise we were asked to use strchr to count the amount of times a single letter appears in a string of text. It needs to count upper or lower cases as equal. It was suggested we use some sort of bit operations.
I managed to get a working program.
But i would like to make the program more interactive by allowing me to use a cin to input the string instead of typing the string directly into the source code (Which was asked by the exercise).
Is it possible to do this? Or is it not possible in the way i wrote this code.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
const char *C = "This is a necesarry test, needed for testing.";
char target = 'A';
const char *result = C;
const char *result2;
int count = 0;
int j[26] ={0};
//================================================================================================================================================
for(int i = 0; i <= 51; i++){
if (i == 26){
target = target + 6;
}
result2 = strchr(result, target);
while(result2 != NULL){
if (result2 != NULL){
result2 = strchr(result2+1, target);
if (i <= 25){
j[i] = j[i] +1;
}
if(i > 25){
j[i-26] = j[i-26] +1;
}
cout << target << "\t";
}
}
cout << target << endl;
target++;
}
char top = 'a';
for(int o = 0; o<= 25; o++){
cout << "________________________________\n";
cout << "|\t" << top << "\t|\t" << j[o] << "\t|" << endl;
top++;
}
cout << "________________________________\n";
}
Simply use getline() to get a string of characters from the console. Using getline you can also consider the spaces in the user input.
string input;
getline(cin, input);
Now to use this with the strchr functionn you simply have to convert this into a C Type string which can be done as follows :
input.c_str
This returns a C type string so you can put this as an arguement to the function,
You will need
#include <string>
This program is supposed to compare the list of consonants to a user input list of letters and print out the number of consonants in the user's input. However, it just prints 0. I'm very new to C++ and am not experienced in finding logic errors.
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int counter(char *, char);
int main()
{
const int size = 51;
char input[size];
const char consonants[22] = "bcdfghjklmnpqrstvwxyz";
cout << "Enter your letters." << endl;
cin >> input;
cout << consonants << "appears";
cout << counter(input, consonants[22]) << "times" << endl;
}
int counter(char *strPtr, char ch)
{
int times = 0;
while (*strPtr != '\0')
{
if (*strPtr == ch)
times++;
strPtr++;
}
return times;
}
I'm aware you're new to C++, and this looks like some kind of exercise you are doing in order to learn, but I will post this answer so you can see how get this done using some of the C++ standar functions.
Using find function from algorithm
string test = "Hello world";
string vowels("aeiuo"); // Its much easier to define vowels than consonants.
int consonants_count = test.length(); // Assume all letters are consonants.
for (auto &c : test) // for each character in test
{
if (find(vowels.begin(), vowels.end(), c) != vowels.end()) // If c is founded inside vowels ...
{
consonants_count--; // Decrement the number of consonants.
}
}
Using regular expressions
#include <regex>
string test = "Hello world"; // A test string.
regex re("a|e|i|o|u"); // Regular expression that match any vowel.
string result = regex_replace(test, re, ""); // "Delete" vowels.
cout << result.length() << endl; // Count remaining letters.
Three problems:
You are not passing an array of consonants, you are passing a single character
You are passing an invalid character (one past the end of the consonant array)
You are counting how many times that invalid character is present.
To fix this problem, make sure that you pass an array as the second parameter, and add a nested loop to iterate that array.
your function counter if checking the input char by char and compare it to a single char(ch).
you need to run your counter function on all the chars in consonants array, or change the counter function:
int count = 0
for(int i = 0; i < 22 ; i ++)
{
count += counter(input, consonants[i])
}
now an even better way will be to count the non consonants characters and then do length-count
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int counter(char *, char);
int main()
{
const int size = 51;
char input[size];
cout << "Enter your letters." << endl;
cin >> input;
cout << consonants << "appears";
cout << counter(input) << "times" << endl;
}
int counter(char *strPtr)
{
int times = 0;
int length = 0;
const char consonants[5] = "aeoui";
while (*strPtr != '\0')
{
for(int i = 0; i < 5 ; i ++)
{
if (*strPtr == consonants[i])
times++;
strPtr++;
length++;
}
}
return length-times;
}
I'm currently learning about vectors and trying to make a palindrome program using them. This is a simple program and so far, I'm trying to make it identify "I am what am I." as a palindrome properly. This is my program so far:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector <string> sentVec;
void getSent(string sent);
void readBackwards(string sent);
int main()
{
string sent;
getSent(sent);
readBackwards(sent);
return 0;
}
void getSent(string sent)
{
cout << "Enter your sentence:" << endl;
getline (cin,sent);
string currentWord, currentLetter;
for (int i = 0; i < sent.length(); i++)
{
currentLetter = sent[i];
if (currentLetter == " ") // inserts word
{
currentWord += sent[i];
sentVec.push_back(currentWord);
currentWord = "";
}
else if (currentLetter == ".") // inserts period
{
sentVec.push_back(currentWord);
currentWord = sent[i];
sentVec.push_back(currentWord);
}
else
{
currentWord += sent[i];
}
}
}
void readBackwards(string sent)
{
string sentForwards, sentBackwards;
// create sentence forwards and backwards without the period.
for (int i = 0; i < sentVec.size() - 1; i++)
{
sentForwards += sentVec[i];
}
for (int j = sentVec.size() - 2; j >= 0; j--)
{
sentBackwards += sentVec[j];
if (j == sentVec.size() - 2)
{
sentBackwards += " ";
}
}
cout << "Sentence forwards is: " << sentForwards << endl;
cout << "Sentence backwards is: " << sentBackwards << endl;
if (sentForwards == sentBackwards)
{
cout << "This sentence reads the same backwards as forwards." << endl;
}
else
{
cout << "This sentence does not read the same backwards as forwards." << endl;
}
}
When I run this program, it prints:
Enter your sentence:
I am what am I.
Sentence forwards is: I am what am I
Sentence backwards is: I am what am I
This sentence does not read the same backwards as forwards.
Why does this not trigger the if loop when comparing the two sentences?
Because sentBackwards isn't the same as sentForwards, because sentBackwards has a trailing whitespace at the end, and thus they aren't the same.
I am unsure how your program detects palindromes, but here is a simple iterative method:
#include <string>
bool isPalindrome(std::string in) {
for (int i = 0; i < in.size() / 2; i++) {
if (in[i] != in[in.size() - 1 - i]) {
return false;
}
}
return true;
}
It returns true if the string passed as an argument is a palindrome
You should not only learn about vector, but also the STL algorithm functions such as std::reverse.
As the other answer given pointed out, one vector has a trailing whitespace. You could have avoided all of that by simply taking the original vector, copying it to another vector, and calling std::reverse. There is no need to write a loop:
void readBackwards()
{
// copy the vector
std::vector<std::string> sentBackwards = sentVec;
// reverse it
std::reverse(sentBackwards.begin(), sentBackwards.end());
// see if they're equal
if (sentVec == sentBackwards)
cout << "This sentence reads the same backwards as forwards." << endl;
else
cout << "This sentence does not read the same backwards as forwards." << endl;
}
This works, since std::vector has an overloaded operator == that compares the items in each of the two vectors and returns true if all items are the same.
In addition to this, reading into a vector can be accomplished much more easily than what you attempted.
#include <sstream>
#include <algorithm>
//...
void getSent(string sent)
{
// remove the periods(s)
auto iter = std::remove_if(sent.begin(), sent.end(), [] (char ch) { return ch == '.';});
sent.erase(iter, sent.end());
// copy the data to a vector
std::istringstream iss(sent);
string currentword;
while ( iss >> currentword)
sentVec.push_back(currentword);
}
Note that we use the std::istringstream to serve as the space delimited parser, alleviating the need to write a loop looking for the space. Also, the std::remove_if algorithm is used to remove any period characters from the string before we start to store the individual strings into a vector.
So basically, the only loop in this whole setup is the while to read from the stream into the vector. Everything else is accomplished by using the algorithm functions, and taking advantage of the various member functions of std::vector (like the overloaded ==)