How to count characters that appear twice consecutively - c++

I'm using C++. So far, my code goes like this:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
int main() {
char word[100]; int ctr, count = 0;
printf("Enter string: "); gets(word);
ctr = 1;
while (word[ctr] != '\0') {
if (word[ctr-1] == word[ctr]) count++;
ctr++;
}
printf("%d", count);
return 0;
}
Sample Run
Enter string: mississippi
3
Enter string: mmmmrrnzzz
6
I've got the first sample run correctly (mississippi) with only 3 characters appearing twice consecutively but not on the second sample run (mmmmrrnzzz) with output 6.
My problem is that, it should not be 6 but 4 instead. 1 for the first two consecutive m, another separate 1 for the next two consecutive m, 1 for r, and 1 for z. I want a separate count for the first "mm" and the second "mm" and also for the "zz" but I don't know how.
I'm a freshman and very new to programming. I wish I could explain better. I'm hoping you could help me. Thank you.

In case of multiple couples like mmmm you need to make a double incrementation of your counter:
#include <stdio.h>
#include <string.h>
int main()
{
char word[100];
int ctr;
int count = 0;
printf("Enter string: ");
gets(word);
int len = strlen(word);
ctr = 1;
while (ctr<len) {
if (word[ctr-1] == word[ctr])
{
count++;
ctr++;
}
ctr++;
}
printf("%d", count);
return 0;
}

First of all the program looks like a C program. In fact you are not using C++. You are using C.:) At least for example in C++ you should use header
#include <cstdio>
instead of
#include <stdio.h>
and so on.
And moreover it has a bug because in general the string can be empty. In this case the condition of the loop skips the first zero-terminating character and the program has undefined behaviour.
Here is a correct approach
#include <stdio.h>
int main( void )
{
const char *s = "mmmmrrnzzz";
size_t count = 0;
while ( *s++ )
{
if ( *s == *( s - 1) )
{
++count;
++s;
}
}
printf( "count = %zu\n", count );
}
The output is
count = 4
Take into account that function gets is unsafe and is not supported by the C (or C++) Standard any more.
You should use function fgets instead of gets.

This will work
#include <stdio.h>
#include <string.h>
int main() {
char word[100]; int ctr, count = 0;
printf("Enter string: "); gets(word);
int len=strlen(word);
ctr = 1;
while (ctr<len) {
if (word[ctr-1] == word[ctr])
{
count++;
ctr++;
}
ctr++;
}
printf("%d", count);
return 0;
}

A standard library version:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
int count{};
std::string s;
std::cin >> s;
for (auto it = s.begin(); (it = std::adjacent_find(it, s.end())) != s.end(); it += 2)
++count;
std::cout << count << '\n';
}

Related

Find sum of numbers in a string without loops in c++

I've found plenty of resources online how how to calculate the sum of numbers in an alphanumeric string, and I've got a working c++ code below.
#include <iostream>
using namespace std;
int findSum(string str)
{
string temp = "";
int sum = 0;
for (char ch: str)
{
if (isdigit(ch))
temp += ch;
else
{
sum += atoi(temp.c_str());
temp = "";
}
}
return sum + atoi(temp.c_str());
}
int main()
{
string str = "t35t5tr1ng";
cout << findSum(str);
return 0;
}
For the example above, "t35t5tr1ng" returns "41".
Now I'm trying to do the same thing, without using any loops.
On the top of my head, I'm thinking arrays, but even then I'm not sure how to parse the values in the array without a for loop of some kind.
Any suggestions or help would be appreciated!
You can use standard algorithms instead of writing loops. Even if it's just a for-loop under the hood, but it can make user code easier to understandby stating the intent.
int findSum(string str)
{
// replace all the non-digits with spaces
std::replace_if(str.begin(), str.end(),
[](unsigned char c) {
return !std::isdigit(c);
}, ' ');
// sum up space separated numbers
std::istringstream iss{str};
return std::accumulate(
std::istream_iterator<int>{iss},
std::istream_iterator<int>{}, 0);
}
Here's a demo.
Here is another solution using std::accumulate:
#include <numeric>
#include <iostream>
#include <string>
#include <cctype>
int findSum(std::string str)
{
int curVal = 0;
return std::accumulate(str.begin(), str.end(), 0, [&](int total, char ch)
{
// build up the number if it's a digit
if (std::isdigit(static_cast<int>(ch)))
curVal = 10 * curVal + (ch - '0');
else
{
// add the number and reset the built up number to 0
total += curVal;
curVal = 0;
}
return total;
});
}
int main()
{
std::string str = "t35t5tr1ng";
std::cout << findSum(str);
return 0;
}

string repetition replaced by hyphen c++

I am a beginner at coding, and was trying this question that replaces all repetitions of a letter in a string with a hyphen: i.e ABCDAKEA will become ABCD-KE-.I used the switch loop and it works, but i want to make it shorter and maybe use recursion to make it more effective. Any ideas?
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char x[100];
int count[26]={0}; //initialised to zero
cout<<"Enter string: ";
cin>>x;
for(int i=0; i<strlen(x); i++)
{
switch(x[i])
{
case 'a':
{
if((count[0]++)>1)
x[i]='-';
}
case 'b':
{
if((count[1]++)>1)
x[i]='-';
}
case 'c':
{
if((count[2]++)>1)
x[i]='-';
}
//....and so on for all alphabets, ik not the cutest//
}
}
Iterate through the array skipping whitespace, and put characters you've never encountered before in std::set, if you find them again you put them in a duplicates std::set if you'd like to keep track of how many duplicates there are, otherwise change the value of the original string at that location to a hyphen.
#include <iostream>
#include <string>
#include <cctype>
#include <set>
int main() {
std::string s("Hello world");
std::set<char> characters;
std::set<char> duplicates;
for (std::string::size_type pos = 0; pos < s.size(); pos++) {
char c = s[pos];
// std::isspace() accepts an int, so cast c to an int
if (!std::isspace(static_cast<int>(c))) {
if (characters.count(c) == 0) {
characters.insert(c);
} else {
duplicates.insert(c);
s[pos] = '-';
}
}
}
return 0;
}
Naive (inefficient) but simple approach, requires at least C++11.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string f(std::string s)
{
auto first{s.begin()};
const auto last{s.end()};
while (first != last)
{
auto next{first + 1};
if (std::isalpha(static_cast<unsigned char>(*first)))
std::replace(next, last, *first, '-');
first = next;
}
return s;
}
int main()
{
const std::string input{"ABCDBEFKAJHLB"};
std::cout << f(input) << '\n';
return 0;
}
First, notice English capital letters in ASCII table fall in this range 65-90. Casting a capital letter static_cast<int>('A') will yield an integer. If after casing the number is between 65-90, we know it is a capital letter. For small letters, the range is 97-122. Otherwise the character is not a letter basically.
Check create an array or a vector of bool and track the repetitive letters. Simple approach is
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str("ABCDAKEAK");
vector<bool> vec(26,false);
for(int i(0); i < str.size(); ++i){
if( !vec[static_cast<int>(str[i]) - 65] ){
cout << str[i];
vec[static_cast<int>(str[i]) - 65] = true;
}else{
cout << "-";
}
}
cout << endl;
return 0;
}
Note: I assume the input solely letters and they are capital. The idea is centered around tracking via bool.
When you assume input charactor encode is UTF-8, you can refactor like below:
#include <iostream>
#include <string>
#include <optional>
#include <utility>
std::optional<std::size_t> char_to_index(char u8char){
if (u8'a' <= u8char && u8char <= u8'z'){
return u8char - u8'a';
}
else if (u8'A' <= u8char && u8char <= u8'A'){
return u8char - u8'A';
}
else {
return std::nullopt;
}
}
std::string repalce_mutiple_occurence(std::string u8input, char u8char)
{
bool already_found[26] = {};
for(char& c : u8input){
if (const auto index = char_to_index(c); index && std::exchange(already_found[*index], true)){
c = u8char;
}
}
return u8input;
}
int main(){
std::string input;
std::getline(std::cin, input);
std::cout << repalce_mutiple_occurence(input, u8'-');
}
https://wandbox.org/permlink/UnVJHWH9UwlgT7KB
note: On C++20, you should use char8_t instead of using char.

How to make recursive function, it needs to check if in a given string the current letter and the one next to it is either lowercase or upper case?

It should convert a string like this: Example: HEloOO, should be converted into : heLOoo . For some reason it doesn't work,it just wont convert the letters from uppercase to lowercase and vice versa any help would be appreciated ?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void rek(char array[], int d)
{
int counter=0;
if(d==0)
{
printf("%s \n",array);
printf("%d \n",counter);
}
else
{
if((array[d]>='A' && array[d]<='Z')&&(array[d-1]>='A' && array[d-1]<='Z'))
{
array[d]=array[d]+32;
array[d-1]=array[d-1]+32;
counter++;
rek(array,d-2);
}
if((array[d]>='a' && array[d]<='z')&&(array[d-1]>='a' && array[d-1]<='z'))
{
array[d]=array[d]-32;
array[d-1]=array[d-1]-32;
counter++;
rek(array,d-2);
}
}
}
int main()
{
char array[100];
int d;
gets(array);
d=strlen(array);
rek(array,d);
return 0;
}
Your function does not call itself when two adjacent characters have different cases. Also you can get different results when the string is processed from the start or from the end.
I would write the function the following way
#include <stdio.h>
#include <ctype.h>
char * rek(char *s)
{
if (s[0] && s[1])
{
size_t i = 1;
if (islower((unsigned char)s[0]) && islower((unsigned char)s[1]))
{
s[0] = toupper((unsigned char)s[0]);
s[1] = toupper((unsigned char)s[1]);
++i;
}
else if (isupper((unsigned char)s[0]) && isupper((unsigned char)s[1]))
{
s[0] = tolower((unsigned char)s[0]);
s[1] = tolower((unsigned char)s[1]);
++i;
}
rek(s + i);
}
return s;
}
int main( void )
{
char s[] = "HEloOO";
puts(rek(s));
return 0;
}
The program output is
heLOoo
The main problem is that you recur only if your have a pair of upper-case or lower-case letters. Otherwise, you drop off the end of your if, return to the calling program, and quit converting things.
The initial problem is that you've indexed your string with the length. A string with 6 characters has indices 0-5, but you've started with locations 5 and 6 -- the final 'O' and the null character.
The result is that you check 'O' and '\0'; the latter isn't alphabetic at all, so you drop through all of your logic without doing anything, return to the main program, and finish.
For future reference, Here's the debugging instrumentation I used. Also see the canonical SO debug help.
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void rek(char array[], int d)
{
int counter=0;
printf("ENTER rek %s %d\n", array, d);
if(d==0)
{
printf("%s \n",array);
printf("%d \n",counter);
}
else
{
printf("TRACE 1: %d %c%c\n", d, array[d-1], array[d]);
if((array[d]>='A' && array[d]<='Z')&&(array[d-1]>='A' && array[d-1]<='Z'))
{
printf("TRACE 2: upper case");
array[d]=array[d]+32;
array[d-1]=array[d-1]+32;
counter++;
rek(array,d-2);
}
if((array[d]>='a' && array[d]<='z')&&(array[d-1]>='a' && array[d-1]<='z'))
{
printf("TRACE 3: lower case");
array[d]=array[d]-32;
array[d-1]=array[d-1]-32;
counter++;
rek(array,d-2);
}
}
}
int main()
{
char *array;
int d;
array = "HEloOO";
d=strlen(array);
rek(array,d);
printf("%s\n", array);
return 0;
}
I come up with this dirty solution:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string solve(const string& str)
{
if (str.empty()) {
return "";
}
if (str.front() >= 'a' && str.front() <= 'z') {
return (char)toupper(str.front()) + solve(str.substr(1));
}
if (str.front() >= 'A' && str.front() <= 'Z') {
return (char)tolower(str.front()) + solve(str.substr(1));
}
}
int main()
{
string str;
cin >> str;
cout << solve(str) << endl;
return 0;
}

Error when trying to reverse string except for special characters

I need to reverse only the parts of the string that are alphabetic while leaving the special characters in the string untouched. For example,
Input: str = "Ab,c,de!$"
Output: str = "ed,c,bA!$"
I have written the following C++ code to do the same:
#include<stdio.h>
#include<iostream>
#include<string>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
using namespace std;
int main() {
char s[100],t[100];
cin>>s;
int len;
for ( len = 0; ; len++ ) {
if( s[len] =='\0') {
break;
}
}
//cout<<len<<endl;
t[len] = '\0';
for ( int i = 0; i < len; i++ ) {
if ( isalpha(s[i])) {
t[len-i-1] = s[i];
// cout<<t[len-i-1]<<endl;
}
else {
t[i] = s[i];
//cout<<t[i]<<endl;
}
}
//cout<<s<<endl;
cout<<t;
return 0;
}
For the above mentioned sample input, I get SOH as the output instead. What is the mistake I am making?
It occurred to me that it would be natural to write this using boost::iterator::filter_iterator and std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
#include <boost/iterator/filter_iterator.hpp>
using namespace std;
int main()
{
auto is_regular = [](char c){return c != ',';};
string s{"hello, cruel world"};
std::reverse(
boost::make_filter_iterator(is_regular, s.begin(), s.end()),
boost::make_filter_iterator(is_regular, s.end(), s.end()));
cout << s << endl;
}
This outputs:
dlrow, leurc olleh
Note that this only treats commas as special, but you get the idea.
Following is a solution that is more along the lines of the the code in your question. I think the problem is that, to do this correctly, you need to have two indices - one running from the left and one from the right - and run until they cross each other. Otherwise you can get all sorts of strange things like things being crossed twice.
#include<stdio.h>
#include<iostream>
#include<string>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<cstring>
using namespace std;
int main()
{
char s[101]="hello, cruel world", t[100];
auto len = strlen(s);
t[len--] = '\0';
//cout<<len<<endl;
int i = 0;
while(i <= len)
if (!isalpha(s[i]))
{
t[i] = s[i];
++i;
continue;
}
else if (!isalpha(s[len]))
{
t[len] = s[len];
--len;
continue;
}
else
{
t[len] = s[i];
t[i] = s[len];
++i;
--len;
}
cout<<t<< endl;
return 0;
}
It is better and more safe to use standard class std::string instead of a character array.
The program can look the following way
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s;
std::getline( std::cin, s );
if ( !s.empty() )
{
for ( std::string::size_type first = 0, last = s.size(); first < --last; ++first )
{
while ( first != last && !std::isalpha( ( unsigned char )s[first] ) ) ++first;
while ( first != last && !std::isalpha( ( unsigned char )s[last] ) ) --last;
if ( first != last ) std::swap( s[first], s[last] );
}
std::cout << s << std::endl;
}
}
If to enter string
Ab,c,de!$
then the output will look like
Ab,c,de!$
ed,c,bA!$

I am getting a segmentation fault in this code and can't understand why?

I am trying to code a program where it takes a program as an input and prints out all the comments written in that program in a separate line.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
for(i=0;str[i]!='/' && str[i+1] !='/';i++);
//cout<<i;
for(i;str[i]!='\n';i++) {
// cout<<i;
cout<<str[i];
}
cout<<endl;
}
return 0;
}
I am getting a segmentation fault in this code and I can't understand why. This is part of a code of a problem in hackerrank https://www.hackerrank.com/challenges/ide-identifying-comments/copy-from/12957153
As commented in your question your code is wrong. First you are treating std::string object, returned by getline, as character array. Secondly your for loops never end if there is no // or \n found in input string. So obviously it will crash. Below is the modified code.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
size_t len = str.length();
const char *cstr = str.c_str();
for(i=0; (cstr[i]!='/' && cstr[i+1] !='/' && i < len); i++)
//cout<<i;
for(; cstr[i]!='\n' && i < len;i++) {
// cout<<i;
cout<<cstr[i];
}
cout<<endl;
}
return 0;
}
int main() {
while(getline(cin,str)) {
int i, len = str.size();
//always make sure that you are not accessing
//contents after your string has ended
for(i=0; i < (len - 1) && !(str[i] == '/' && str[i+1] == '/'); i++);
//note that i here might be the last alphabet
//if there's no comment
if(i < len && str[i] != '/')
i++;
//checking if str[i] != '\n' is not a good idea
//as c++ stl strings are not temrinated by '\n'
if(i < len) {
for(; i < len; i++)
cout << str[i];
cout << endl;
}
}
return 0;
}
Also note that both of the following codes won't terminate at the 4th character, c++ stl strings are not terminated by these characters.
string str = "hahahaha";
str[4] = '\n';
cout << str;
str[4] = '\0';
cout << str;
This is much easier to write and probably much faster than the other solutions to date.
#include <iostream>
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
size_t loc = str.find("//");
if (loc != str.npos)
{
std::cout << str.substr(loc + 2)<< std::endl;
}
}
return 0;
}
It is also wrong.
Here is a nice, clean, and simple state machine version. Also pretty close to worst-case for speed. Thing is it's closest to being right, even though it is also wrong.
#include <iostream>
enum states
{
seeking1,
seeking2,
comment
};
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
states state = seeking1;
for (char ch:str)
{
switch (state)
{
case seeking1:
if (ch == '/')
{
state = seeking2;
}
break;
case seeking2:
if (ch == '/')
{
state = comment;
}
else
{
state = seeking1;
}
break;
case comment:
std::cout << ch;
break;
}
}
if (state == comment)
{
std::cout << std::endl;
}
}
return 0;
}
Why are these approaches all wrong? Consider the line
cout << "Hi there! I am \\Not A Comment!" << endl;`
You can't just look at the \\, you also need the context. This is why the state machine above is the better option. It can be modified to handle, at the very least, states for handling strings and block comments.