reverse of the string using recursion - c++

Hey guys i get stuck in the unusual situation. This is my code, it works perfectly for returning the reverse of the string but it gives output with including the space so I don't want that space to be included in my programme output so anyone has suggestions about this plz share it... by the way this is my code :
#include <iostream>
using namespace std;
string reverse(string str, int size) {
if (size == -1)
return "";
else
{
char a;
a = str[size];
return a + reverse(str, size - 1);
}
}
int main() {
int size;
cout << "the size of the string : ";
cin >> size;
string str;
cout << "enter the word : ";
cin >> str;
cout << reverse(str, size);
}

Since you use std::string, you don't need to specify the size of the string, but use the std::string::size() or std::string::length() member functions. Also, a = str[size]; is problematic when size equals to the size of the string, since you perform an out of bound access (remember that C++ uses zero-based indexing). You can simplify the code a lot, ending up with
#include <iostream>
#include <cstddef> // for std::size_t
using namespace std;
string reverse(string str, std::size_t pos) {
return (pos == 0 ? "" : str[pos - 1] + reverse(str, pos - 1));
}
int main() {
string str;
cout << "enter the word : ";
getline(cin, str); // allow for spaces in the string
cout << reverse(str, str.size()) << endl;
}
Here, instead of using cin >> str, I used getline(cin, str), since cin reads up to the first whitespace, whereas getline allows to read strings that containg spaces.

Change the implementation of the function reverse to the following.
string reverse(string str ,int size){
if (size==-1)
return "";
else
{
char a;
a=str[size];
if (' ' == a )
return reverse(str,size-1)
else
return a+reverse(str,size-1);
}
}
Alternatively, do some pre-processing on th input.

Related

Write a C++ code to count the number of a’s in a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I've written the code below, but it's giving a number of errors:
15 13 C:\Users\admin\Desktop\Untitled1.cpp [Error] no match for 'operator==' (operand types are 'std::string {aka std::basic_string<char>}' and 'char')
15 28 C:\Users\admin\Desktop\Untitled1.cpp [Error] no match for 'operator==' (operand types are 'std::string {aka std::basic_string<char>}' and 'char')
16 3 C:\Users\admin\Desktop\Untitled1.cpp [Error] expected ')' before 'count'
And some more.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int len,i,count=0;
string str[len];
cout<<"Enter the length for your string:";
cin>>len;
cout<<"Enter the characters for your string:";
for(i=0;i<len;i++)
cin>>str[i];
for(i=0;i<len;i++)
{
if(str[i]=='a'||str[i]=='A')
count++;
}
cout<<"Number of 'a' and 'A' in your string is "<<count<<".";
return 0;
}
You're making this WAY too hard.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int count=0;
string str;
cout<<"Enter the characters for your string:";
getline(cin, str);
for (char c: str) {
if (c == 'a' || c == 'A')
count++;
}
cout<<"Number of 'a' and 'A' in your string is "<<count<<"." << endl;
return 0;
}
My changes from yours:
I got rid of len and the index. You don't need them.
I used getline() to get an entire line. The loop is just silly.
I used a simpler form of a for-loop to loop through the characters.
And I added an endl to the final cout.
One major reason to favour std::string over plain character arrays is that std::string can resize easily. You need not tell a std::string its size beforehand.
This:
string str[len];
Is an array of strings. Its size is len, but len is uninitialized, hence your code has undefined behavior.
A single string is this:
std::string str;
You don't need to, but if you still want you can resize a string upfront. Though if you do that you still should not keep track of its size seperately from the string. It has a size() method and to loop all characters in the string you can use a range-based loop:
std::string str;
std::cout << "Enter the length for your string:";
std::cin >> len;
str.resize(len);
std::cout << "Enter the characters for your string:";
for(auto& c : str) std::cin >> c;
str[i] is then the i-th character in the string. In your code str[i] is the i-th string in the array. Thats why you get an error about mixing characters ('A') and strings (str[i]).
You are declaring an array of strings (and doing so incorrectly at that). Then you are filling the array with len number of strings not characters, and then trying to compare each string to a single character. But std::string does not have an operator== for that comparison, which is exactly what the first 2 errors are telling you.
Get rid of the array, you should be working with a single std::string instead, eg:
#include <iostream>
#include <string>
int main()
{
int len, i, count = 0;
char ch;
std::string str;
std::cout << "Enter the length for your string:";
std::cin >> len;
std::cout << "Enter the characters for your string:";
for (i = 0; i < len; ++i)
{
std::cin >> ch; // or: std::cin.get(ch)
str.push_back(ch);
}
for (i = 0; i < len; ++i)
{
if (str[i] == 'a' || str[i] == 'A')
++count;
}
std::cout << "Number of 'a' and 'A' in your string is " << count << ".";
return 0;
}
You can take that a step further by also getting rid of len too, let std::cin populate the string for you, eg:
#include <iostream>
#include <string>
int main()
{
int count = 0;
std::string str;
std::cout << "Enter your string:";
std::cin >> str; // or: std::getline(std::cin, str);
for (size_t i = 0; i < str.size(); ++i)
{
if (str[i] == 'a' || str[i] == 'A')
++count;
}
std::cout << "Number of 'a' and 'A' in your string is " << count << ".";
return 0;
}
And then you can get rid of the for loop too, by using the standard std::count_if() algorithm, eg:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str;
std::cout << "Enter your string:";
std::cin >> str; // or: std::getline(std::cin, str);
size_t count = std::count_if(str.begin(), str.end(),
[](char ch){ return (ch == 'a' || ch == 'A'); }
);
std::cout << "Number of 'a' and 'A' in your string is " << count << ".";
return 0;
}
This declares an array of std::string's, not a single string with the length len:
string str[len];
Instead declare a std::string and use std::getline to read whatever it is that the user types in. You can then use std::ranges::count_if (or std::count_if prior to C++20) to count the number of a:s and A:s in the string:
#include <algorithm> // std::ranges::count_if, std::count_if
#include<iostream>
#include<string>
int main() {
std::string str;
std::cout << "Enter the characters for your string:";
std::getline(std::cin, str);
// a lambda to check if an individual character is an 'a' or 'A'
auto a_or_A_lambda = [](char ch) { return ch == 'a' || ch == 'A'; };
// use count_if and with the lambda
auto count = std::ranges::count_if(str, a_or_A_lambda);
// prior to C++20:
//auto count = std::count_if(str.begin(), str.end(), a_or_A_lambda);
std::cout << "Number of 'a' and 'A' in your string is "<< count << ".\n";
}

How to Replace character in c++ without using library

I have prototype - int replace_char(string &, char);
I can't use library from string and ctype.h, I should write my own function.
So the task is to find in the text caharacter, which should I should replace with "*" .
example: In This is my text .
replace all t to * . Result will be - *his is my *ex*.
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
cout << ""Please insert text:"
cin >> str;
}
int replace_char(string str, char c1)
{
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1)
str[i]='*';
}
return str;
}
There were several errors in the code:
The function signature mismatches, the prototype is defined as std::string& but in the function definition, std::string only was used.
The program never converted the capital letter T or anything which is capital in order to convert them before comparing each letter with a single char.
The function is never used in the code.
cin >> str won't take longer texts followed by next whitespace character.
The function wants to return an integer, but actually returned type was a std::string, which is totally a misunderstanding.
The code redefined:
#include <iostream>
// taking a reference of std::string and a char
int replaceText(std::string&, char);
int main(void) {
std::string s;
int rep;
std::cout << "Enter a string: ";
std::getline(std::cin, s); // getline() to accept whitespaces
// since we're using a reference, the original variable is manipulated
int rep = replaceText(s, 't');
std::cout << "Output: " << s << std::endl;
std::cout << "Replaced number of chars: " << rep << std::endl;
return 0;
}
int replaceText(std::string& str, char c) {
size_t len = str.length();
static int count;
// changing each letter into lowercase without using any built-in functions
for (size_t i = 0; i < len; i++)
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + 32;
// replacing the character, the main work
for (size_t i = 0; i < len; i++)
if (str[i] == c) {
str[i] = '*';
count++; // count a static variable
}
return count; // returning the overall counts
}
The program firstly takes an input from the user of type std::string and uses reference to the variable str. Now the program enters to the function code.
In the beginning, the function converts each letter to lowercase without using any library or a built-in function. Afterwards, it tries to compare each letter of the string carefully and as soon the given character matches a value containing in the string passed to the function, it replaces and counts a static variable which keeps the value save for the entire program life.
Thereafter, it simply displays the manipulated string.
It outputs something like:
Enter a string: This is a text
Output: *his is a *ex*
Replaced chars: 3
You seem to have a good start.
You need to declare str before reading input into it. Try string str;
Then you need to use your function in main. Either store its output into another string like string replaced = replace_char(str, 't');
Or put it into the output directly like cout << replace_char(str, 't') << endl;
Probably this is what you need
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
string str;
cout << "Please insert text:"
std::getline(cin, str);
int rlen = replace_text(str, 't')
cout << str << endl;
cout << "Number of replaced : " << rlen << endl;
return 0;
}
int replace_char(string str, char c1)
{
int rlen = 0;
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1) {
str[i]='*';
rlen++;
}
}
return rlen;
}
Given the prototype of the function, I'm guessing you need to return the number of chars replaced. This implementation should work:
#include <string>
#include <iostream>
using namespace std;
int replace_char(string &, char);
int main ()
{
cout << "Please insert text:";
string str;
getline(cin, str);
int nCharsReplaced = replace_char(str, 't');
}
int replace_char(string& str, char c1)
{
int count = 0;
for (int i = 0 ; i < str.length(); i++)
{
if(str[i]==c1)
{
str[i]='*';
count++;
}
}
return count;
}
Keep in mind there's no need to return the string, as you're passing it by reference, so the argument itself is modified.
Also, if you want the example you provided to work the replace_char functions cannot be case sensitive, since you replaced the capital 'T' with '*' too. In order to achieve that, you could implement a function that turns every char to lowercase (ideally, you would use tolower from ctype):
char to_lower_case(char c)
{
return c - ('Z' - 'z');
}
And replace the if condition with:
if (to_lower_case(str[i]) == c1)
If you don't understand how this work, take a look at how ASCII works.

Insert a character into a string

I need to insert a character into a string at every instance of that character. For example if my string was, "This is a test" and my character was 's' then my output would need to look like this: "Thiss iss a tesst"
any idea why this isn't working? Here's what I have so far. I am not supposed to add any extra preprocessor instructions or anything, just using what's here I need to figure this out.
#include <iostream>
#include <string>
using namespace std;
int main(){
string userString;
char userChar;
cin >> userString;
cin >> userChar;
for (int i = 0; i < userString.size(); i++){
if(userString.at(i) == userChar){
userString.insert(userString.begin() + i, userChar);
}
}
cout << userString;
return 0;
Update:
Here's the solution I worked out.
#include <iostream>
#include <string>
using namespace std;
int main(){
string userString;
char userChar;
cout << "enter a string" << endl;
getline(cin, userString);
cout << "enter a character" << endl;
cin >> userChar;
for (int i = userString.size()-1; i >= 0; i--){
if(userString.at(i) == userChar){
userString.insert(userString.begin() + i, userChar);
}
}
cout << userString;
return 0;
}
I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.
#include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
#include <string>
#include <iostream>
int main()
{
std::cout << "Enter a string: ";
std::string userString; // define variables as close
std::getline(std::cin, userString);
std::cout << "Enter a character: ";
char userChar; // to where they're used as possible
std::cin >> userChar;
for (std::size_t i{}; i < userString.size(); ++i) {
if (userString[i] == userChar) { // no need to use std::string::at() 1)
userString.insert(userString.begin() + i, userChar);
++i; // advance the index to not read the same character again.
}
}
std::cout << userString << '\n';
}
1) since it is allready sure that the index will be in a valid range.
Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.
std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:
std::string& duplicate_char(std::string& str, char val)
{
using std::string;
auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
while (pos != string::npos)
{
str.insert(pos, 1, val); // insert at pos one character val
pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character
}
return str;
}
You may use this function like this:
int main()
{
std::string testStr{"Thiss iss a tesst"};
duplicate_char(testStr, 's');
std::cout << testStr << std::endl;
}

Trying to temporarily convert entire string to lowercase and remove spaces

So my program is a palindrome checker function using only the string library and C++ sting objects. In order to check if the string input by the user is a palindrome, I need to convert the entire string to lowercase and remove the spaces to check if the string and its reverse are equal. I've tried looking up solutions but I've only found answers using different libraries and creating new functions. This is the code I have so far.
#include <iostream>
#include <string>
using namespace std;
string checkPalin();
int main()
{
string result = checkPalin();
cout << "The palindromes are: " << result;
}
string checkPalin()
{
int stringNum, time = 0;
string list;
string str1;
string reverse;
cout << "How many strings? " << endl;
cin >> stringNum;
cout << "Enter the strings: " << endl;
do
{
getline(cin, str1);
int size = str1.length();
for (int i = size - 1; i >= 0; i--)
reverse += str1[i];
if ((str1.compare(reverse)) == 0)
{
list += str1;
}
time++;
} while (time <= stringNum);
return list;
}
How about something like this
std::string inputString = "WhatEver", cleanString;
for (char & c : inputString)
if (c != ' ')
cleanString += std::tolower(static_cast<unsigned char>(c));
std::tolower is undefined if the char value is not representable as unsigned char, hence the cast.

How do you parse a c-string?

Hi I'm trying to take a c-string from a user, input it into a queue, parse the data with a single space depending on its contents, and output the kind of data it is (int, float, word NOT string).
E.g. Bobby Joe is 12 in 3.5 months \n
Word: Bobby
Word: Joe
Word: is
Integer: 12
Word: in
Float: 3.5
Word: months
Here's my code so far:
int main()
{
const int maxSize = 100;
char cstring[maxSize];
std::cout << "\nPlease enter a string: ";
std::cin.getline(cstring, maxSize, '\n');
//Keyboard Buffer Function
buffer::keyboard_parser(cstring);
return EXIT_SUCCESS;
}
Function:
#include <queue>
#include <string>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <vector>
namespace buffer
{
std::string keyboard_parser(char* input)
{
//Declare Queue
std::queue<std::string> myQueue;
//Declare String
std::string str;
//Declare iStringStream
std::istringstream isstr(input);
//While Loop to Read iStringStream to Queue
while(isstr >> str)
{
//Push onto Queue
myQueue.push(str);
std::string foundDataType = " ";
//Determine if Int, Float, or Word
for(int index = 0; index < str.length(); index++)
{
if(str[index] >= '0' && str[index] <= '9')
{
foundDataType = "Integer";
}
else if(str[index] >= '0' && str[index] <= '9' || str[index] == '.')
{
foundDataType = "Float";
break;
}
else if(!(str[index] >= '0' && str[index] <= '9'))
{
foundDataType = "Word";
}
}
std::cout << "\n" << foundDataType << ": " << myQueue.front();
std::cout << "\n";
//Pop Off of Queue
myQueue.pop();
}
}
}
Right now with this code, it doesn't hit the cout statement, it dumps the core.
I've read about using the find member function and the substr member function, but I'm unsure of how exactly I need to implement it.
Note: This is homework.
Thanks in advance!
UPDATE: Okay everything seems to work! Fixed the float and integer issue with a break statement. Thanks to everyone for all the help!
Your queue is sensible: it contains std::strings. Unfortunately, each of those is initialised by you passing cstring in without any length information and, since you certainly aren't null-terminating the C-strings (in fact, you're going one-off-the-end of each one), that's seriously asking for trouble.
Read directly into a std::string.
std::istreams are very useful for parsing text in C++... often with an initial read of a line from a string, then further parsing from a std::istringstream constructed with the line content.
const char* token_type(const std::string& token)
{
// if I was really doing this, I'd use templates to avoid near-identical code
// but this is an easier-to-understand starting point...
{
std::istringstream iss(token);
int i;
char c;
if (iss >> i && !(iss >> c)) return "Integer";
}
{
std::istringstream iss(token);
float f;
char c; // used to check there's no trailing characters that aren't part
// of the float value... e.g. "1Q" is not a float (rather, "word").
if (iss >> f && !(iss >> c)) return "Float";
}
return "Word";
}
const int maxSize = 100; // Standard C++ won't let you create an array unless const
char cstring[maxSize];
std::cout << "\nPlease enter a string: ";
if (std::cin.getline(cstring, maxSize, '\n'))
{
std::istringstream iss(cstring);
std::string token;
while (iss >> token) // by default, streaming into std::string takes a space-...
token_queue.push(token); // ...separated word at a time
for (token_queue::const_iterator i = token_queue.begin();
i != token_queue.end(); ++i)
std::cout << token_type(*i) << ": " << *i << '\n';
}