How to Replace character in c++ without using library - c++

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.

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";
}

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;
}

c++ c-string topper function sometimes outputs random numbers in the end

I need to use a character array pointing to a function. In the function, I need it to make the input into all capital letters. I figured I'd use the toupper function, which worked great for certain input, but when I input certain words I end up getting weird symbols/numbers in the end of my output(see output). Any help?
Code
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
void allUppercase(char*);
const int SIZE = 50;
int main()
{
char words[SIZE];
cout << "Please enter your text : ";
cin.get(words, (SIZE-1));
cout << "The keyboard input was \"" << words << "\".\n";
cout << "\nThe uppercase output is \"";
allUppercase(words);
cout << "\".\n";
return 0;
}
// outputs the string entered in uppercase letters
// (Use a character array to store the string)
void allUppercase(char *ch)
{
char temp[SIZE];
for (int i=0; i < SIZE; i++)
{
if (ch[i] != '\0')
temp[i] = toupper(ch[i]);
else
break;
}
cout << temp;
}
Example Output
You forgot to null terminate temp.
void allUppercase(char *ch) {
char temp[SIZE];
for (int i=0; i < SIZE; i++) {
if (ch[i] != '\0') {
temp[i] = toupper(ch[i]);
} else {
temp[i] = '\0';
break;
}
}
cout << temp;
}
You just need to add a zero byte at the end of the result string.
For example,
void allUppercase( char const* s )
{
char temp[SIZE];
int i = 0;
while( temp[i] = toupper( s[i] ) ) { ++i; }
cout << temp;
}
Disclaimer: code not touched by compiler.
In other news, in order to work with national characters such as Norwegian æ, ø and å, with a single byte per character encoding that supports them, you need to
cast the argument to toupper to unsigned char, and
call setlocale( LC_ALL, "" ) at the start of main.
Without the cast toupper can receive a negative argument value other than EOF, because char is usually a signed type, and in that case the behavior is undefined (e.g. a crash).
Also, instead of raw arrays and pointers, just use std::string. You have already included the <string> header.
the best way is to write a while loop like this
while(ch[i]!='\0')
{
temp[i] = toupper(ch[i]);
cout<<temp[i]
i++;
}
and this program will be terminated when '\0' is found

reverse of the string using recursion

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.

How to Convert a C++ String to Uppercase

I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}