How to check if a string ends with 'ed' in C++; - c++

How to write a program that reads 5 strings from user input and prints only those strings that end with the letter ‘ed’ in C++. Need help!

The solution is rather straightforward.
First we define a container that can contain 5 std::string. For that we use a std::vector together with a constructor to reserve space for the 5 elements.
Then we copy 5 strings from the console (from user input) into the vector.
And, last, we copy elements out of the std::vector to std::cout, if the strings end with "ed".
Because of the simplicity of the program, I cannot explain much more . . .
Please see.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
constexpr size_t NumberOfTexts = 5U;
int main()
{
// Define a container that can hold 5 strings
std::vector<std::string> text(NumberOfTexts);
// Read 5 strings from user
std::copy_n(std::istream_iterator<std::string>(std::cin), NumberOfTexts, text.begin());
// Print the strings with ending "ed" to display
std::copy_if(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout,"\n"), [](const std::string& s){
return s.size()>=2 && s.substr(s.size()-2) == "ed";
});
return 0;
}

Simple solution,
#include<iostream>
using namespace std;
bool endsWith(const std::string &mainStr, const std::string &toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
int main()
{
string s[5];
for(int i=0;i<5;i++)
{
cin>>s[i];
}
for(int i=0;i<5;i++)
{
if(endsWith(s[i],"ed"))
cout<<s[i]<<endl;
}
}
Hope This might Helps:)

Related

To remove the Duplicates from the given string (without sorting it) [duplicate]

This question already has answers here:
Remove duplicates from the string in CPP
(8 answers)
Closed 1 year ago.
The question is asking to remove duplicates from the string, I came up with a solution to remove duplicates but for that, I sorted the string.
So I wanted to know is there a way of removing duplicates from a string without sorting the string.
Test Cases :
"allcbcd" -> "alcbd"
My Code (the one in which string has to be sorted) :
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
if (s.length() == 0)
{
return "";
}
sort(s.begin(), s.end());
char ch = s[0];
string ans = removeDup(s.substr(1));
if (ch == ans[0])
{
return ans;
}
return (ch + ans);
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
Make a boolean array of size 256 considering only ASCII values.
Loop over the string and check the ASCII index value of the character in the array. If it is already set to true, then ignore that character. If not, add that character to your resultant string and set the ASCII index value to true in the array.
Finally, print the resultant string.
If you want to make it support for UTF-8 chars, use a map instead of an array.
Here is one way to do it without sorting (or using a recursive loop):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
string::size_type index = 0;
string::iterator end = s.end();
while (index < s.size()) {
end = remove(s.begin()+index+1, end, s[index]);
++index;
}
s.erase(end, s.end());
return s;
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
Online Demo

How to capitalize the first letter of each name in an array?

Here is the question:
Create a function that takes an array of names and returns an array where only the first letter of each name is capitalized.
example
capMe(["mavis", "senaida", "letty"]) ➞ ["Mavis", "Senaida", "Letty"]
And the code I wrote to answer this question:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void capme(vector<string> name)
{
char ch;
for(int i = 0; i < name[i].size(); i++)
{
putchar(toupper(name[i][0]));
cout << name[i] << endl;
}
}
int main()
{
vector <string> name = {"mavis", "senaida", "letty"};
capme(name);
return 0;
}
As you can see, it prints "Mmavis", "Ssenaida", "Lletty", which is wrong. Can you guys help me in answering this question as I don't know how?
To change the input argument, we have two choice: make the argument mutable reference, or add a return type, here I choose the first one.
putchar can be used to print only one character, it recommended to use cout to print a string, possible solutions:
with traditional loop: capme
with range for-loop since c++11 : capme2
with stl algorithm transform: capme3
Don't forget to check if the string element is empty, or you may crash while accessing the first character.
To obey the single-responsibility principle (SRP), it's better to print the string vector out of the capme function.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void capme(vector<string>& name) {
for (int i = 0; i < name[i].size(); i++) {
if (name[i].empty()) continue;
name[i][0] = toupper(name[i][0]);
}
}
void capme2(vector<string>& names) {
for (auto& name : names) {
if (name.empty()) continue;
name[0] = toupper(name[0]);
}
}
void capme3(vector<string>& names) {
std::transform(names.begin(), names.end(), names.begin(), [](auto& s) {
return s.empty() ? s : (s[0] = toupper(s[0]), s);
});
}
Online demo
You have used the wrong function. What you need is a replacement and not a prepend. Try using std::string::operator[] to access the first element of the words in the vector. This is how I would write this code:
std::vector<string> capitaliseInitLetter(std::vector<string> vec) {
for (auto& word : vec) {
word[0] -= 32; //add a check to see if the letter is already capital
}
return vec;
}
The above code is just an example which assumes that the input is valid. You'll have to add checks and exception handling for invalid inputs on your own. (Hint: Take a look at #prehistoricpenguin's answer)
You are calling putchar() which writes a character to standard output, and in this case is printing the first letter of each string in name as uppercase, then you are writing the entire string to standard output immediately after.
Additionally, your function does not meet the requirements you stated above saying it should return an array where the strings have the first letter capitalized.
What you could do is change the signature of capme() to return a std::vector<std::string>, and perhaps utilize the for_each() function to handle changing the first letter of each string in your vector then return it.
For reference:
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
std::vector<std::string> capme(std::vector<std::string> name)
{
std::for_each(name.begin(), name.end(), [](std::string &s) {
s[0] = toupper(s[0]);
});
return name;
}
Or as kesarling suggested, a simple for each loop:
std::vector<std::string> capme(std::vector<std::string> name)
{
for (auto& s : name) {
s[0] = toupper(s[0]);
}
return name;
}

How to remove consonants from a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Here is my code:
#include <iostream>
#include <string>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
while(n--)
{
string str;
char a[] = {'a','e','i','o','u','A','E','I','O','U'};
getline(cin, str);
for(int i=0 ;i<str.length(); i++)
{
for(int j=0; j<10; j++)
{
if(str[i]==a[j])
{
cout << str[i];
}
}
}
cout << "\n";
}
return 0;
}
Test cases are :
HmlMqPhBfaVokhR
wdTSFuI
IvfHOSNv
I am not removing anything but I am printing only vowels. But, some test cases didn't pass. Maybe this code doesn't work on multiple test cases.
Try this for proper console in :
int main()
{
int n;
std::cin >> n;
std::cin.ignore(); // fix
/* remaining code */
return 0;
}
> To find the vowels in a string
On way of finding the vowels in a string is using a std::binary_search each character of the given string in a vowel table.
Make a sorted array of char s of all vowels(i.e. vowels array).
For each char of the input string, std::binary_search in the
vowels array.
If std::binary_search returns true(meaning the char is an vowel), print the char of the string.
Following is the example code! (See live online)
#include <iostream>
#include <string>
#include <algorithm> // std::for_each, std::binary_search, std::sort
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
const std::string str{ "HmlMqPhBfaVokhR wdTSFuI IvfHOSNv" };
std::for_each(str.cbegin(), str.cend(), [&](const char str_char)
{
if (std::binary_search(a.cbegin(), a.cend(), str_char))
std::cout << str_char << " ";
});
return 0;
}
Output:
a o u I I O
> To remove the vowels from a string
Use erase-remove idiom as follows(till c++17†).
Make a sorted array of char s of all vowels(i.e. vowels array).
Using std::remove_if, collect the iterators pointing to the characters, which are vowels. A lambda function can be used as the predicate for std::remove_if, where the std::binary_search is used to check the char in the string exists in the vowels array.
Using std::string::erase, erase all the collected characters(i.e. vowels) from the string.
Following is an example code! (See live online)
#include <iostream>
#include <string>
#include <algorithm> // std::sort, std::binary_search, std::remove_if
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
std::string str{ "Hello World" };
// lambda(predicate) to check the `char` in the string exist in vowels array
const auto predicate = [&a](const char str_char) -> bool {
return std::binary_search(a.cbegin(), a.cend(), str_char);
};
// collect the vowels
const auto vowelsToRemove = std::remove_if(str.begin(), str.end(), predicate);
// erase the collected vowels using std::string::erase
str.erase(vowelsToRemove, str.end());
std::cout << str << "\n";
return 0;
}
Output:
Hll Wrld
† Since c++20, one can use std::erase_if for this, which would be less error prone than the the above one. (See online live using GCC 9.2)
#include <iostream>
#include <string> // std::string, std::erase_if
#include <array> // std::array
int main()
{
std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
std::sort(a.begin(), a.end()); // need sorted array for std::binary_search
std::string str{ "Hello World" };
// lambda(predicate) to check the `char` in the string exist in vowels array
const auto predicate = [&a](const char str_char) -> bool {
return std::binary_search(a.cbegin(), a.cend(), str_char);
};
std::erase_if(str, predicate); // simply erase
std::cout << str << "\n";
return 0;
}
> To remove the consonants from a string
To remove the consonants from the given string, in the above predicate negate the result of std::binary_search. (See live online)
const auto predicate = [&a](const char str_char) -> bool {
return !std::binary_search(a.cbegin(), a.cend(), str_char);
// ^^ --> negate the return
};
As side notes,
Avoid the #include<bits/stdc++.h> Read more: Why should I not #include <bits/stdc++.h>?
Do not practice with using namespace std; Read more: Why is "using namespace std;" considered bad practice?
Apart from the std::getline problem already answered:
for(int i=0 ;i<str.length(); i++)
{
for(int j=0; j<10; j++)
{
if(str[i] == a[j])
{
// this is the one you do NOT want to print...
// cout<<str[i];
// skip instead:
goto SKIP;
}
}
std::cout << str[i]; // output the one NOT skipped...
SKIP: (void)0;
}
OK, don't want to start any discussion about usage of goto, there are many ways to avoid it, e. g. by packing the inner for loop into a separate (inline) function. You can have it easier, though, as there already exists such a function; code gets even easier with a range-based for loop:
for(auto c : str)
{
if(!strchr("aeiouAEIOU", c))
{
std::cout << c;
}
}
strchr (from cstring) returns a pointer to the first character in the string equal to the reference character - or nullptr if not found...
To really remove the vowels from the string in a modern C++ way, consider this:
str.erase(std::remove_if(
str.begin(), str.end(),
[](char c) { return strchr("aeiouAEIOU", c) != nullptr; }
), str.end());
Your code probably should looks like (please see comments inline):
#include <iostream>
#include <string>
using namespace std;
int main() {
string vowels = "aeiouAEIOU";
int n;
cin>>n; // assume this stands for line count
while(n-- >= 0)
{
string str, result;
getline(cin, str);
for(int i=0 ;i<str.length(); i++)
{
if (vowels.find(str[i]) != std::string::npos)
result += str[i]; // add character to result if it is not consonant
}
cout<<result<<"\n"; // print result
}
return 0;
}

Atoi function while reading a .csv file C++

The execution of my code crashes when it gets to the "atoi" function, but I cannot understand why.
The code is supposed to read a matrix from a .csv file, considering:
- the first row (so till the first '\n') and saving each element (separated by a ',') in a vector of ints; - the rest of the matrix, by looking at each element and creating a specific object if the number read is 1 or 2.
I don't get any exception while debugging the program, it just crashes during the execution (and using the system ("PAUSE") I could figure out it was the atoi function which didn't work properly).
Can you help me understand what is going wrong?
Thank you very much.
Ps: I also attached all the libraries I'm loading... maybe it can help :)
#include <fstream>
#include <stdio.h>
#include <sstream>
#define nullptr 0
#include <string>
#include "classi.h"
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
ifstream file("problem.csv");
unsigned int N = 0;
unsigned int M = 0;
char c; //modificato char * c;
unsigned int i=0,j=0, k=0, n_iter, j_temp =0;
std::vector<car> v_row;
std::vector<car> v_col_temp;
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
std::string iterazioni; //location where I want to save the first row as a string and then cut it into pieces (iteraz) and then convert (atoi --> iter)
std::string iteraz;
while(!file.eof()){
std::getline(file,iterazioni,'\n');
stringstream it(iterazioni);
while (it.good()) {
std::getline(it,iteraz, ',');
iter[k] = atoi(iteraz.c_str());
if(iter[k]<0){
cout<<"Errore: negative #of iterations"<<endl;
break;
}
iter.push_back(0);
k++;
}
iter.pop_back();
file.get(c);
if (c=='1'){
blue_car b(i,j);
if (v_col_temp[i].get_next() != nullptr)
v_col_temp[i].insert_tail(&b);
else
v_col_temp[i].insert_head(&b);
}
if (c=='2'){
red_car r(i,j);
if (v_row[i].get_next() != nullptr)
v_row[i].insert_tail(&r);
else
v_row[i].insert_head(&r);
}
if (c==',') {
j++;
if (i == 0)
j_temp++;
}
if (c=='\n'){
car p;
v_row.push_back(p);
v_col_temp.push_back(p);
i++;
if (j != j_temp) {
std ::cout<<"errore input non valido: numero righe/colonne non coerente"<<endl;
}
j=0;
}
else if ((c!='\n') && (c!=',') && (c!='0') && (c!='1') && (c!='2'))
std ::cout<<"errore input non valido"<<endl;
};
n_iter = k-1;
M=i;
N=j+1;
...
Your program crashes because you failed to initialize the contents of the iter vector.
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
You declare and construct this vector. The vector is empty at this point, and it has no elements.
At some point later:
iter[k] = atoi(iteraz.c_str());
The initial value of k is 0, so this attempts to assign the return value from atoi() to iter[0].
The problem is, of course, there is no iter[0]. The iter vector is still empty, at this point.
Additional comments, which is sadly true for at least 50% of these kinds of questions on stackoverflow.com:
1) "using namespace std"; is a bad practice, that should be avoided
2) Do not use system("pause") as well, as you referenced in your question.

Why is replacing an element of a vector so slow?

I notice that amending (or replacing) an element in a large vector is consuming a lot of time when the vector is getting bigger, even when the element's place in the vector is known.
Is there an explanaition for this?
I use an unsorted set as an index. The code first tries to find the element in the set with set.find(). If the element not present in the set the code insert it at the end of the set and at the same time pushes it at the end of the vector.
If the element is found on position "x" of the set the data in the vector is replaced by using:
vector.at(x)=vector[x]+element.
When I skip the vector part and only insert the element in the set the code easily processes 95 million elements in less then 2 minutes. But when I add the vector part to it the code keeps on running for hours.
The file I'm importing is a semicolumn separated text, with below structure
2161182;Jutfaseweg;footway;no;7740068,13877901
2953564;Timorkade;cycleway;no;7785429,368846814,582743212,582743202,582743213,582743203,582743214,582743206,582743210,45200603
Each line represents a way. The ID's in the last element are waypoints of that particular way. Each element has a righthand neighbour, unless it is the last element of the way and based on the 4th element ("yes" or "no", meaning oneway or not), also a lefthand neighbour, unless it is the first element of the way.
Below is the code as requested
#include <windows.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <set>
#include <vector>
using namespace std;
set<string>PresentStreet;
set<int>PresentNode;
vector<string>NeighBours;
string line1;
void split(const string& s, char c,
vector<string>& v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
int main(int argc, char *argv[]) {
ifstream myfile ("filename.txt");
int CounterLine=1;
while ( getline (myfile,line1) ) {
string s1=line1;
vector<string> v1;
split(line1, ';', v1);
PresentStreet.insert(v1[2]);
vector<string> v2;
split(v1[4], ',', v2);
for (int t=0;t<v2.size();t++) {
auto search = PresentNode.find(atoi(v2[t].c_str()));
if(search == PresentNode.end()) {
string Neighbours="";
if(v1[3].find("no")!=std::string::npos&&t>0) {
Neighbours=Neighbours+v2[t-1]+",";
}
if(t<v2.size()-1) {
Neighbours=Neighbours+v2[t+1]+",";
}
stringstream ss;
ss<<CounterLine;
stringstream ss2;
ss2<<v2[t];
PresentNode.insert(atoi(v2[t].c_str()));
NeighBours.push_back(Neighbours);
}else{
int nPosition = distance (PresentNode.begin (), search);
string Neighbours=NeighBours[nPosition];
if(v1[3].find("no")!=std::string::npos&&t>0) {
Neighbours=Neighbours+v2[t-1]+",";
}
if(t<v2.size()-1) {
Neighbours=Neighbours+v2[t+1]+",";
}
NeighBours.at(nPosition)=Neighbours;
}
}CounterLine++;
}
}