This question already has answers here:
C++ : Creating an array with a size entered by the user
(3 answers)
Closed 3 years ago.
In One Of My Question , I Need To Get 'n' String And After I Get The Strings , I Should Process With Them:
{
int n=0;
cin>>n;
string user[n];
for(int i=0;i<n;i++)
{
cin>>user[n];
}
}
After I Get String How I Can Process With Them And Compare Them?
For Example If I Enter This Strings : "asdabdabmsd" and "ajksdasbgdjkabs" , How I Can Compare Specified Word In This Two String With Together?
First, get the length of two strings.After that use two loops for two strings and compare both strings character by character.
Firstly , correct the way you are storing strings. It should be cin>>user[i]
{
int n=0;
cin>>n;
std::vector <std::string> user(n);
for(int i=0;i<n;i++)
{
cin>>user[i]; // it should be 'i' not 'n'
}
}
Secondly, if you want to compare, say second letter of first string with the fourth letter of third string, use user[0][1] == user[2][3]
Means to get the ith letter of jth string, use user[j-1][i-1]
Instead of cin to get the input string, you need to use getline() (http://en.cppreference.com/w/cpp/string/basic_string/getline) or else if the input string contains white space the remaining part of the input string will not be ignored.
Related
This question already has an answer here:
C++ string and string literal comparison
(1 answer)
Closed 1 year ago.
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input -
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output -
If the word t is a word s, written reversely, print YES, otherwise print NO.
When I write this code, the output is wrong -
int main(){
char s[100000],a[100000];
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
But when I write this code, the output is correct -
int main(){
char s[100000];
string a;
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
Why is it like this, is there a rule that a character array cannot be compared to another character array and if so, how can it be compared to a string?
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing.
In short, what you're really doing is:
if(&s[0] == &a[0])
And those two pointers will never be equal.
To compare the contents of character arrays, you need to use strcmp() or similar function instead, eg:
if(strcmp(s, a) == 0)
Since you're programming in C++, please use std::string for all your strings. There are overloads for the == operator that do the right thing if you have std::string values.
This question already has answers here:
Change string by index
(3 answers)
Closed 7 years ago.
string l;
cin>>l[0];
cout<<l;
input:a
output:
According to me the code must print the value of l[0] but why is there no output?
You need to do
cin>>l;
In your current state of code, when you try to access l[0] you are trying to access a memory location which may or may not be there. cin >> l[0] doesn't changes the size of the string which remains 0.
So when you try to do cout << l you are effectively printing an empty string.
Another alternative is
string s;
s.resize(1);
You have an empty string. There are no characters in it, including 0th character, you trying to read into. You need to actually add characters in string:
std::string l;
l.push_back('\0'); //Or any other character
std::cin >> l[0];
This question already has answers here:
how to check string start in C++
(11 answers)
Closed 7 years ago.
I have a vector composed of strings, some strings have single words, some have multiple words, some have numbers, etc. I have a code that deletes elements of the vector IF the entire string is one specific word ("event") that works perfectly:
for (int j = 0; j< myvec.size()-1; j++) {
if(myvec[j] == "<event>") { //erase all instances of "<event>"
myvec.erase(myvec.begin()+j);
}
}
However, now I need to delete a few elements in the vector that only START with a word (these all have differing junk after that first key word "wgt"
I have no idea how to get this working. I'm assuming it will be something similar to the above for/if loop, I just don't know how to make the if statement only look at the first word in the string.
Any ideas?
Thanks in advance!
The first line places string beginning with 'abc' at the end, and the second erases them from the vector.
auto end_it = std::remove_if(myvec.begin(), myvec.end(),
[](const string &str){
return str.find("abc") == 0 ;}) ;
myvec.erase(end_it, myvec.end()) ;
Basically what I'm looking for is a way to set the contents of an array -ex: a phrase- into individual words to be compared.
so when the user enters the data, I can tell how many words of the same length they are.
void main(){
char array[30];
int length, cont, array_tokens;
printf("enter a phrase: ");
scanf("%[^\n]s", array); //or gets(array); which ever one you like
/*-------------------------
*******magic happens*******
---------------------------*/
for(int i=0; i<wordcount;i++)
printf("%d word(s) with %d letters was entered", array_tokens, cont);//some sort of
system("pause"); //counter which came
} //with the magic that
//happened before
so the result should be:
enter a phrase: user entered a phrase with similar lentgh words
1 word(s) with 1 letter was entered
2 word(s) with 4 letters was entered
1 word(s) with 5 letters was entered
3 word(s) with 6 letters was entered
1 word(s) with 7 letters was entered
Well, strtok() is one way to solve this problem. If you're aiming for efficiency (you should), you should write a loop which iterates over the letters in the sentence. Count the number of non-space characters encountered since the last white-space, and update the n-letter-word-frequency array whenever you get a white-space. I could've written the code to do this, but I don't want to deprive you of the sense of gratification when you write the working piece of code yourself. :P
You can have an array count where count[i] is the number of words of length i.
Set count to 0
Set t to 0
for(int i=0;i<given_phrase.length();i++)
{
if(given_phrase[i]==' ')
{
count[t]++;
t=0;
}
else
{
t++;
}
}
For C, simply check for '\0' for end of phrase.
Then you can display results based on count.
You'll want to split up the sentence into tokens (in this case individual words) by a delimiter (in this case a space char ' '). There are various ways to do that. A good old-school C method is to use strtok as Robert Harvey suggested, which is provided by the C Standard Library. It works by passing in the string you want to split up, followed by the delimiter at which to split the string.
Then, to count the similar length words, try having integer variables for the different word lengths (or more simply in a sort of frequency array, each index representing a word of that length and its value being a count of their occurrences), looping over all the word tokens, incrementing the corresponding variable when a word of a length is encountered. To obtain the length of a C-Style string, try strlen.
I am a newbie in programing and stuck at a point where I have to compare the two strings using C++: string 1 and string 2 for the same characters and then delete those characters from string 1 and print the string 2. Looking forward for your help. My code goes like this:
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
string first_string;
string second_string;
string::size_type start_position=0;
cout<<"Please enter the first string: "<<endl;
getline(cin,first_string);
cout<<"Please enter the Second string: "<<endl;
getline(cin, second_string);
while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
second_string.replace( start_position, first_string.size(), "" );
start_position++;
}
}
cout<<"The Result is as follws: "<<second_string<<endl;
getch();
return 0;
}
Looking forward for your help.
Regards,
Sam
Compare each char in string2 with all chars of string1. If that char from string2 doesn't match any in string1 then append this char to a new string else continue without appending. Continue this for all chars in string2. Now assign the new string as string1. This uses extra o(n) space but is simpler.
I would recommend using c_str to represent your string as an array of characters (or even better begin with an array of characters rather than the string datatype). After you do this write a function to go through each array and compare characters (removing where required), its a bit inefficient but it'll do the job and its simple.