This question already has an answer here:
Counting characters in words in a C++ console application
(1 answer)
Closed 9 years ago.
Is there anyway to show that character s appears 5 times in the string is there any function to sort out the character and than show us that the character appears 5 or 6 times in the string.
#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you"
//now i want to show the l character appears several time.
//and i need help here.
system("pause");
}
You can use std::count
int lcount = std::count(a.begin(), a.end(), 'l');
Just keep counting using a pointer until nul character is reached and keep increasing an integer on successful comparison.
#include<iostream>
#include<string>
int main(){
using namespace std;
string a="hello how are you";
char *p = &a[0];
int c = 0;
do
{
if(*p == 'l')
c++;
}while(*p++);
cout << c;
}
You can walk over any container, including a string and do what you like with it.
You could count how many instances of each character. You may want to consider ignoring whitespace.
std::string a("hello how are you");
std::map<char,int> count;
for(auto c : a)
{
++count[c];
}
Related
This question already has answers here:
std::string length() and size() member functions
(4 answers)
Closed 2 years ago.
We have some word, that we should identify the length of. How can I do that?
Example INPUT: "hello" - without quotes;
Example OUTPUT: 5
If input is contained in a std::string you can find the length as stated by Ravi.
If it's a C string you find the length with
int len = strlen(INPUT);
In C/C++ upper case is normally used for constants so it's better to name the string input, not INPUT.
string str;
cin>>str;
//use this
cout<<str.length();
//or use this
cout<<str.size();
both of them will work fine.
There is one function to find length in C++.
You can try by using:
input.length()
Also remember, you need to include:
#include <iostream>
using namespace std;
Refer this document :
https://www.w3schools.com/cpp/cpp_strings_length.asp
You can use input.length() or input.size().
Or you can use this simple loop.
for (i = 0; str[i]; i++)
;
cout << i << endl;
This question already has answers here:
Compare equality of char[] in C
(5 answers)
Closed 6 years ago.
The for loop reverses original string 's' and stores it in 'temp.'Temp is printed correctly. After which, s and temp are compared, but the result always shows NO. :(
#include<cstring>
#include <iostream>
using namespace std;
int main()
{
char s[100], temp[100];
cin >> s;
cout << strlen(s);
for(int i=0;i<strlen(s);i++)
{
temp[i]=s[strlen(s)-i];
}
cout << "temp is" << temp;
if(temp==s)
{
cout << "YES";
}
else
{
cout << "NO";
}
return 0;
}
You should use strcmp instead of == because the latter is merely a pointer comparison. Also, '\0' has to be used to end your string. And your current code would actually create an empty string because your string at position strlen(s) contains '\0'.
Then again, you should not work with char arrays in C++ on your own, rather use std::string as already pointed out in comments.
This question already has answers here:
C++ Comparison of String Literals
(8 answers)
Closed 7 years ago.
I would like to understand the result of the below code in Microsoft visual studio C/C++ (2012 version). Indeed, when the solution is generated, the result is “1” (True). However, the word “a” is less than the word “z” in ASCII table. So, the result should be “0” (False). Even if I inverse the operation, mean ("z" > "a"). The result is “1”. I tried also this operation ("a" < "z") and ("z" < "a"), the result was “0” for the both
Anyone can explain me what’s happening?
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << ("a" > "z") << endl;
}
Your code is almost the same as if you had written:
const char s1[2] = {'a'};
const char s2[2] = {'z'};
int main()
{
cout << (s1 < s2) << endl;
}
So you can see that your code is actually comparing the addresses of two character arrays.
This question already has answers here:
Replace multiple spaces with one space in a string
(5 answers)
Closed 9 years ago.
I wrote a program which is supposed to remove excess spaces from a string. But it only shows characters before spaces. It finds a space and checks the character after that whether it is a space. Depending on excess spaces it shifts other characters over excess spaces. But output is very confusing.
input: "qwe(2 spaces)rt(one space)y"
output: "qwe(one space)rt(one space)y"
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string a;
cin >> a;
int len = a.length();
int new_len=len;
int z,s=0;
for(int i=0; i<new_len; i++){
if(a[i]==' '){
z=i+1;
s=0;
//Assigning the number of excess spaces to s.
while(a[z]==' '){
s++;
z++;
}
//doing the shifting here.
if(s>0){
for(int l=i+1; l<new_len-s; l++){
a[l]=a[s+l];
}
}
new_len-=s;
}
}
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
Most of your code is semi-pointless -- when you use the normal string extractor (stream >> string) it automatically skips across all consecutive leading white-space, and stops reading at the first whitespace character. As such, it's already doing almost everything the rest of your code is intended to accomplish. That leaves a much simpler approach to accomplishing the same task:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
This does have one problem: it'll leave one extra space at the end of the output. If you don't want that, you can use the infix_ostream_iterator I've posted previously. With that, you'd change the above to something like this:
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
infix_ostream_iterator<std::string>(std::cout, " "));
If you're using C++11 doing this your way is overkill - you can just use a regex. Something like the following should do it (untested):
#include <regex>
#include <iostream>
#include <string>
using namespace::std;
int main(){
string a;
cin >> a;
regex r(" +");
a = regex_replace(a,r," ");
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
Your code is highly ineffective. Imagine a following string with 1,000,000 characters:
a a a a a a a...
Each time your algorithm encounters a second space, it goes through the whole string to shift it one char left. I would attempt another approach:
Create two iterators, like realPos and charPos. Set them to 0 at the beginning.
Create a variable, which stores a number of spaces encountered so far, like spacesSeen. Set it to 0.
Now, while realPos is lower than length of the whole string:
If string[realPos] != ' ' and charPos != realPos, make an assignment: string[charPos] = string[realPos]. Then increase both realPos and charPos by one. Set spacesSeen to 0.
If string[realPos] == ' ' and spacesSeen == 0, increase spacesSeen by one, copy characters and advance both iterators.
If string[realPos] == ' ' and spacesSeen > 0, then increase spacesSeen and then increase only realPos.
Now charPos marks the place where your final string ends, adjust strings size, such that it ends there.
In simpler words: copy the characters one by one and skip multiple spaces on the way.
This is my code here i am trying to find the biggest length of same length characters at a time like "a a a bb bb bc sa sa a a" so answer is 5 for two characters at a time for 5 times adjacently .
this is my code , my question is that when i am trying to take the input , for my first input it is not going to getline but printf in last lines and then it takes a line and prints output
like if i give
5 it writes 1 then it takes getline , but i want it to take getline first rather than printf, in this way for my 5 input it prints 1 and 4 desired outputs .i want 5 desired can you tell me why..
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
int a,j;
scanf("%d",&a);
for(j=0;j<a;j++)
{
vector<int> v;
string s;
getline(cin,s);
int i,cnt =0;
for(i=0;i<s.length();i++)
{
if(s[i] != ' ')
{
cnt++;
}
else
{
v.push_back(cnt);
cnt =0;
}
}
v.push_back(cnt);
int k=0;
int ps =0;
int sp=0;
while(k<v.size()-1)
{
if (v[k+1] - v[k] == 0)
{
sp++;
k++;
}
else
if (sp >= ps)
{
ps = sp;
k++;
sp=0;
}
else
{
k++;
sp=0;
}
}
if (sp<ps)
printf("%d",ps+1);
else
printf("%d",sp+1);
}
return 0;
}
You shouldn't be mixing scanf with getline, try to only use one or the other (and getline is a better option).
What is happening is that scanf stops parsing once it has finished reading an int. It does not consume the end of line character you type, or anything else you could have entered after that number. So getline picks up whatever was left on that first line (possibly just the newline char).
A "quick" but dirty fix would be to change your scanf call so that it swallows the whitespace after the int:
scanf("%d ",&a);
// ^ notice the space there
But that's not a real fix. Use getline and a string stream (in <sstream>) to get the first number, and your code will work as you intend it to. You'll find examples of using the istringstream to extract a number in this FAQ: How to convert a number to string and vice versa in C++
You might also be interested in this other question:
Split a string in C++?, the answers demonstrate ways to split a string that are less error-prone than what you're doing here.
How are you entering everything exactly? I think the problem may be that your getline() is reading your last [enter] off of the stream, thus automatically putting an empty string into s. That would result in the 1 you're getting. Try this for your scanf:
scanf("%d\n",&a)
That should absorb the [enter].