find and replace words in C++ - c++

I have a program to find and replace words in C++.
#include<iostream.h>
#include<string.h>
int main()
{
char string[80], replace[80], found[80], str1[80], str2[80], str3[80];
cout << "\nEnter string(max 3 words)\n";
cin.getline(string , 80);
cout << "\nEnter the word to be Found\n";
cin.getline(found , 80);
cout << "\nReplace with \n";
cin.getline(replace , 80);
for(int i = 0; string[i] != '\0'; i++)
{
str1[i] = string[i];
if(str1[i] == " ")
break;
}
for(int j = i; string[j] != '\0'; j++)
{
str2[j] = string[j];
if(str2[j] == " ")
break;
}
for(int k = j; string[k] != '\0'; k++)
{
str3[k] = string[k];
if(str3[k] == " ")
break;
}
cout << str1;
cout << str2;
cout << str3;
}
For this I stored every word as a different string, but it doesn't help.
What should be done to improve this?

Your code has too many logical & syntactical error.
Here is the modified code which will accept the required string and print expected output:
#include<iostream>
#include<string.h>
using namespace std;
void strreplace(string orgString, const string search, const string replace )
{
for( size_t pos = 0; ; pos += replace.length() )
{
pos = orgString.find( search, pos );
if( pos == string::npos )
break;
orgString.erase( pos, search.length() );
orgString.insert( pos, replace);
cout<<"String after replacement:"<<orgString<<endl;
}
}
int main()
{
char string[80], replace[80], found[80], str1[80], str2[80], str3[80] ;
cout << "\nEnter string(max 3 words)\n" ;
cin.getline(string , 80);
cout <<"\nEnter the word to be Found\n";
cin.getline(found , 80);
cout <<"\nReplace with \n" ;
cin.getline(replace , 80);
strreplace(string, found, replace);
return 0;
}
I hope this will help you.

In your current code you need to:
Use single quotes to compare characters for equality, not double quotes
Increment another index in your second and third loops. This is because the index for str2 and str3 needs to start at 0, not at the current position being looked at in string
Initalize the main string index (i) in second and third loops with (current value + 1) to skip past the space that it is currently at.
Null terminate your str1, str2, str3
1
if(str1[i] == " ")
should be
if(str1[i] == ' ')
2,3 Instead of
for(int j = i;string[j] != '\0' ; j++)
do
for (int j = 0, i = (i + 1); string[i] != '\0'; j++,i++)
The assignment becomes
str2[j] = string[i];
Do the same for the 3rd loop (without the int in front of j or use another letter). For consistency you could add a j variable starting at 0 to the first loop as well.
4 After each loop add an assignment statement for the null terminator (every c-string needs '\0' at the end to work properly) :
str1[i] = '\0';
str2[j] = '\0';
str3[j] = '\0';

std::string doesn't contain such function instead you could use stand-alone replace function from algorithm header.
#include <algorithm>
#include <string>
string stringReplace(std::string toSearch, std::string toReplace, std::string originalString) {
std::replace( originalString.begin(), originalString.end(), 'toSearch', 'toReplace'); // replace all 'toSearch' to 'toReplace'
return originalString;
}

Related

Check if given string is palindrome c++ iterative method

#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cout << "Enter a string: ";
getline(cin, str);
int length = str.length();
string temp;
int k = 0;
for(int i = length-1; i>=0; i--){
temp[++k] = str[i];
}
cout<<temp;
return 0;
}
Actually, i want to find out whether the given string is a palindrome or not, so i am storing the first string in second one in reverse order , and then will ultimately check whether they are equal or not, but i am unable to print out even the result of temp string
You defined an empty object of the type std::string
string temp;
So you may not use the subscript operator with the empty object in the loop.
int k = 0;
for(int i = length-1; i>=0; i--){
temp[++k] = str[i];
}
Using your approach you could just write
string temp( str.rbegin(), str.rend() );
without using a loop.
However to check whether a string is a palindrome there is no need to create an intermediate string.
You could do it in a loop the following way.
std::string::size_type i = 0;
for ( auto n = str.length(); i < n / 2 && str[i] == str[n - i - 1]; )
{
++i;
}
if ( i == str.length() /2 ) std::cout << str << " is a palindrome\n";
Or without the loop and defining one more variable you could write
if ( str == std::string( str.rbegin(), str.rend() ) )
{
std::cout << str << " is a palindrome\n";
}

My Code for Erasing Empty Spaces in a Sentence in C++ has an Issue

I have made this code such that whatever I type in a sentence has the first letter of the first word capitalized; While reducing any number of spaces in a sentence to just one space. However, my sentences are only reducing by one space. For example, if I put 3 spaces in a sentence, the output has spaces reduced by 1 to 2 spaces, but I want the output of words in a sentence to have only one space. I can't quite figure out what is wrong with my code and hence any help would be greatly appreciated. I have attached my code for reference below:
#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int i = 0; //i for counter
string str;
//String variable
getline(cin, str); //Get string from user
int L = str.length(); //Find length of string
//Display original string
for (int i = 0; i < 100; i++)
{
str[i] = tolower(str[i]);
}
str[0] = toupper(str[0]);
bool space;
for (int j = i + 1; j < L; j++)
{
str[j] = str[j + 1];
L--;
}
cout << str << endl;
return 0;
}
Or doing it in a more modern way using iterators :
#include <iostream>
#include <cctype>
int main() {
std::cout << "This is the string trimming function.\n" <<
"Throw in a string and I will make sure all extra spaces " <<
"will be reduced to single space.\n";
std::string InputString, TrimmedString;
int head = -1;
int tail = -1;
std::cout << "Please enter the input string :\n" << std::endl;
std::getline(std::cin, InputString);
for(std::string::iterator it = InputString.begin(); it <= InputString.end(); it++){
if (*it != ' ' && head < 0 && tail < 0) {
head = std::distance(InputString.begin(), it);
}
else if (head >= 0 && tail < 0 && (*it == ' ' || it == InputString.end())) {
tail = std::distance(InputString.begin(), it);
TrimmedString.append(InputString, head, (tail-head));
TrimmedString.push_back(' ');
head = -1;
tail = -1;
}
}
TrimmedString[0] = toupper(TrimmedString[0]);
std::cout << "\nThe processed string is :\n\n" << TrimmedString << std::endl;
return 0;
}
Try this:
int main()
{
std::string str;
std::getline(cin, str);
//Change case
str[0] = toupper(str[0]);
std::transform(str.begin() + 1, str.end(), str.begin() + 1, ptr_fun<int, int>(tolower));
//Parsing time
for (int i = 0; i <= str.size() - 1; i++)
{
if (str[i] == ' ' && str[i + 1] == ' ') //if present & next are whitespaces, remove next
{
str.erase(str.begin() + i);
i--; // rechecking condition
}
}
std::cout << '\n' << str << '\n';
}
Output:

Replacing Spaces With "%20" - String Subscript Out Of Range

I'm going through a coding interview book and got stuck on a question: Replace all spaces in a string with '%20'.
I tried running this solution in my compiler but got this error: String Subscript Out Of Range. So, I looked up stackoverflow for that error and got a solution to try to append new chars with += instead of just assigning new chars to the string but that still produced the same error.
Here's my code. Thanks so much for your time!
void replaceSpaces(string &str)
{
int spaces = 0;
// Count number of spaces in original string
for (int i = 0; i < str.size(); i++)
{
if (str[i] == ' ')
spaces++;
}
// Calculate new string size
int newSize = str.size() + (2 * spaces);
str.resize(newSize); // thanks Vlad from Moscow
// Copy the chars backwards and insert '%20' where needed
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
str[newSize - 1] = '0'; // += '0' didnt work
str[newSize - 2] = '2'; // += didnt work
str[newSize - 3] = '%'; // same
newSize = newSize - 3;
}
else
{
str[newSize - 1] = str[i]; // same
newSize--;
}
}
}
int main()
{
string test = "sophisticated ignorance, write my curses in cursive";
replaceSpaces(test);
cout << test << endl;
}
You did not resize string str.
You set variable newSize
int newSize = str.size() + (2 * spaces);
larger than str.size() and use it like an index in str
str[newSize - 1] = str[i];
At least you could write at first
str.resize( newSize );
Here is a demonstrative program that shows how the function can be written
#include <iostream>
#include <string>
std::string & replaceSpaces( std::string &s )
{
std::string::size_type spaces = 0;
// Count number of spaces in original string
for ( char c : s ) if ( c == ' ' ) ++spaces;
if ( spaces != 0 )
{
auto i = s.size();
// Calculate new string size
auto j = s.size() + 2 * spaces;
s.resize( j );
// Copy the chars backwards and insert '%20' where needed
while ( i != j )
{
if ( s[--i] == ' ' )
{
s[--j] = '0';
s[--j] = '2';
s[--j] = '%';
}
else
{
s[--j] = s[i];
}
}
}
return s;
}
int main()
{
std::string test = "sophisticated ignorance, write my curses in cursive";
std::cout << "\"" << test << "\"\n";
std::cout << "\"" << replaceSpaces( test ) << "\"\n";
}
The program output is
"sophisticated ignorance, write my curses in cursive"
"sophisticated%20ignorance,%20write%20my%20curses%20in%20cursive"
EDIT: After you inserted a statement with resize as I adviced then in the loop
for (int i = str.size() - 1; i >= 0; i--)
^^^^^^^^^^^^^^^^^^^^^^
variable i must be initialized with the old size of the string that it had before resizing it.
If you are looking for a practical solution without being overly concerned with performance, here's something much simpler:
void replaceSpaces(string &str) {
str = std::regex_replace(str, std::regex(" "), "%20");
}
How about this?
#include <iostream>
#include <string>
std::string replaceSpaces(std::string str)
{
std::string newStr;
for (char c : str)
{
if (c == ' ')
newStr.append("%20");
else
newStr.push_back(c);
}
return newStr;
}
int main()
{
std::string test = "sophisticated ignorance, write my curses in cursive";
std::string newtest = replaceSpaces(test);
std::cout << test << std::endl << newtest << std::endl;
}

Splitting char array

I have a char **names array that basically stores names from a file.
This is my .txt file
Mike, Sam, Stuart
Andre, Williams, Phillips
Patels, Khan, Smith
Basically, I want to split and store the names before the , character.
For example, Mike, Sam, Stuart will become...
newName[0] = Mike
newName[1] = Sam
newName[2] = Stuart
I have something like this...
for (int i=0; i<3; i++)
{
for (int j=60, j>0; j--)
{
if(names[i][j] == ',')
{
cout << j << endl; //THIS PRINTS OUT THE POSITION. HOW CAN I STORE THE POSITION AND DO SOMETHING?
}
}
}
I would appreciate it if someone could help me with my code, it is in the right direction. I don't want to use any vectors classes
I have attempted to store marks of these students, however I want to add it to a double *marks[2] array.
This is my .txt file...
69.9, 56.5
29.8, 20.0
35.6, 45.0
This is my code...
char **values;
char * pch;
pch = strtok (values[i], " ,");
while (pch != NULL)
{
sscanf(pch, "%f, %f", &marks[i][0], &marks[i][1]);
pch = strtok (NULL, " ,");
}
I am getting random values such as 1.28277e-307 and 1.96471e+257
look up the strtok command it will be very helpful to you.
This code looks for hyphen characters and prints stuff... change it to commas
#include <string.h>
#include <stdio.h>
int main()
{
const char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char * newName[100]; /* at most 100 names */
int iCurName = 0;
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL )
{
printf( " %s\n", token );
newName[iCurName] = malloc (char *) (strlen(token) + 1);
strcpy(newName[iCurName],token);
iCurrName ++;
token = strtok(NULL, s);
}
return(0);
}
Use function strtok() to split input line into tokens; use strcpy_s() to copy each token into name buffer.
Note 1: The strtok() function replaces each separator with '\0' character, so the line variable cannot be declared with const. If your input buffer must be constant, for example if you want to use the whole line for something else, make a copy of it before calling strtok() function.
Note 2: You might want to trim space in addition to splitting your input line.
#define MAX_LINE_LENGTH 80
#define MAX_NAME_LENGTH 20
#define MAX_NAMES_PER_LINE 3
const char constInput = "Mike, Sam, Stewart";
char line[MAX_LINE_LENGTH];
strcpy_s(line, MAX_LINE_LENGTH, constInput);
char *separator = ",";
char newName[MAX_NAMES_PER_LINE][MAX_NAME_LENGTH];
int i = 0;
char *token = strtok(line, separator);
while ((i < MAX_NAMES_PER_LINE) && ((token = strtok(NULL, separator)) != NULL))
{
strcpy_s(newName[i++], MAX_NAME_LENGTH, token);
}
char newName[3][60];
for (int i=0; i<3; i++){
int r=0, c=0;
for (int j=0; j<60; j++){
if(names[i][j] == ',' || names[i][j] == '\0'){
newName[r++][c] = '\0';
c = 0;
if(names[i][j] == '\0'){
cout << newName[0] << '\n'
<< newName[1] << '\n'
<< newName[2] << '\n' << endl;
break;
}
while(names[i][++j] == ' ')
;
--j;
} else {
newName[r][c++] = names[i][j];
}
}
}
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inf("data.txt");
double marks[2];
char ch;
while(inf.good()){
inf >> marks[0] >> ch >> marks[1];
cout << "mark1:" << marks[0] << endl;
cout << "mark2:" << marks[1] << endl;
}
}
I don't know if this function works fast enough, but here it is:
char** split_quotes(char *input, char separator = ' ', bool keep_quotes = false)
{
if (&input && input)
{
size_t length = strlen(input);
char **chunks = new char*[length];
bool inQuotes = false;
size_t count = 0, from = 0;
for (size_t i = 0; i < length; i++)
{
if (input[i] == '"')
{
inQuotes = !inQuotes;
}
else if (input[i] == separator && !inQuotes)
{
size_t strlen = i - from;
if (strlen > 0)
{
if (!keep_quotes && input[from] == '"' && input[i - 1] == '"')
{
from++; strlen -= 2;
}
chunks[count] = new char[strlen + 1]();
strncpy(chunks[count], &input[from], strlen);
count++;
}
from = i + 1;
}
}
if (from < length)
{
size_t strlen = length - from;
if (!keep_quotes && input[from] == L'"' && input[length - 1] == L'"')
{
from++; strlen -= 2;
}
chunks[count] = new char[strlen + 1]();
strncpy(chunks[count], &input[from], strlen);
count++;
}
// Save chunks to result array //
char **result = new char*[count + 1]();
memcpy(result, chunks, sizeof(char*) * count);
// free chunks //
delete[] chunks;
return result;
}
return NULL;
}
Usage:
wchar_t **name = split_quotes(L"Mike,Donald,\"My Angel\",Anna", L',');
if (name)
{
while (*name++)
{
std::wcout << "Person: " << *name << std::endl;
}
}

How can I reverse the words in a sentence without using built-in functions?

This was the interview question:
How to convert Dogs like cats to cats like Dogs ?
My code shows: cats like cats. Where am I making the mistakes?
#include <iostream>
using namespace std;
int main()
{
char sentence[] = ("dogs like cats");
cout << sentence << endl;
int len = 0;
for (int i = 0; sentence[i] != '\0'; i++)
{
len++;
}
cout << len << endl;
char reverse[len];
int k = 0;
for (int j = len - 1; j >= 0; j--)
{
reverse[k] = sentence[j];
k++;
}
cout << reverse << endl;
int words = 0;
char str[len];
for (int l = 0; reverse[l] != '\0'; l++)
{
if (reverse[l] == ' ' || reverse[l] == '\0') // not sure about this part
{
for (int m = l; m >= 0; m--)
{
str[words] = reverse[m];
words++;
}
}
}
cout << str;
return 0;
}
I know you can do this using pointers, stack, vectors... but interviewer was not interested in that!
This is a fixed version of your sample code:
Your principal problem is that every time you found and ' ' or '\0' you copy the bytes of the reverse string from the beginning to that point. Example in loop 5 you copy from index 0-5 (stac) from reverse to str in reverse order, but in in loop 10 you copy from index 0-10 (stac ekil) from reverse to str in reverse order, until here you have already the printed result string ('cats like cats'), and the same in loop 15 all of this incrementing the index of str, in the last loop you are written pass the end of the valid memory of str (and because of that not printed as output).
You need to keep track when end the last word reversed to reverse only the actual word, and not the string from the beginning to the actual index.
You don't want to count the special character (' ' and '\0') in the reversing of the words, you would end with cats like\0dogs
Modified sample code provided:
#include <iostream>
using namespace std;
int main() {
char sentence[] = ("dogs like cats");
cout << sentence << endl;
int len = 0;
for (int i = 0; sentence[i] != '\0'; i++) {
len++;
}
cout << len << endl;
char reverse[len];
int k = 0;
for (int j = len - 1; j >= 0; j--) {
reverse[k] = sentence[j];
k++;
}
cout << reverse << endl;
int words = 0;
char str[len];
// change here added last_l to track the end of the last word reversed, moved
// the check of the end condition to the end of loop body for handling the \0
// case
for (int l = 0, last_l = 0; ; l++) {
if (reverse[l] == ' ' || reverse[l] == '\0')
{
for (int m = l - 1; m >= last_l; m--) { // change here, using last_t to
str[words] = reverse[m]; // only reverse the last word
words++; // without the split character
}
last_l = l + 1; // update the end of the last
// word reversed
str[words] = reverse[l]; // copy the split character
words++;
}
if (reverse[l] == '\0') // break the loop
break;
}
cout << str << endl;
return 0;
}
Some code, written with the restriction of using the most simple features of the language.
#include <iostream>
// reverse any block of text.
void reverse(char* left, char* right) {
while (left < right) {
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
int main() {
char sentence[] = "dogs like cats";
std::cout << sentence << std::endl;
// The same length calculation as sample code.
int len = 0;
for (int i = 0; sentence[i] != '\0'; i++) {
len++;
}
std::cout << len << std::endl;
// reverse all the text (ex: 'stac ekil sgod')
reverse(sentence, sentence + len - 1);
// reverse word by word.
char* end = sentence;
char* begin = sentence;
while (end < sentence + len) {
if (*end != ' ')
end++;
if (end == sentence + len || *end == ' ') {
reverse(begin, end - 1);
begin = end + 1;
end = begin;
}
}
std::cout << sentence << std::endl;
return 0;
}
Dissecting your algorithm in pieces. First, you find the length of the string, not including the null char terminator. This is correct, though could be simplified.
size_t len = 0;
for (int i = 0; sentence[i] != '\0'; i++) {
len++;
}
cout << len << endl;
This could easily be written simply as:
size_t len = 0;
while (sentence[len])
++len;
Next, you reverse the entire string, but the first defect surfaces. The VLA (variable length array) you declare here, (which you don't need and shouldn't use, as it is a C++ extension and non-standard) does not account for, nor set, a terminating null-char.
char reverse[len]; // !! should be len+1
int k = 0;
for (int j = len - 1; j >= 0; j--) {
reverse[k] = sentence[j];
k++;
}
// !! Should have reverse[k] = 0; here.
cout << reverse << endl; // !! Undefined-behavior. no terminator.
This temporary buffer string is not needed at all. There is no reason you can't do this entire operation in-place. Once we calculate len correctly, you simply do something like the following to reverse the entire sequence, which retains the null char terminator in proper position:
// reverse entire sequence
int i = 0, j = len;
while (i < j--)
{
char c = sentence[i];
sentence[i++] = sentence[j];
sentence[j] = c;
}
Next we move to where you try to reverse each internal word. Again, just as before, the buffer length is not correct. It should be len+1. Worse (hard to imagine), you never remember where you left off when finding the end point of a word. That location should be the next point you start checking for, and skipping, whitespace. Without retaining that you copy from current point all the way back to the beginning of the string. which essentially blasts cats over dogs.
int words = 0;
char str[len]; // !! should be len+1
for (int l = 0; reverse[l] != '\0'; l++)
{
if (reverse[l] == ' ' || reverse[l] == '\0') // not sure about this part
{
for (int m = l; m >= 0; m--) {
str[words] = reverse[m];
words++;
}
}
}
cout << str; //!! Undefined behavior. non-terminated string.
Once again, this can be done in-place without difficulty at all. One such algorithm looks like this (and notice the loop that reverses the actual word is not-coincidentally the same algorithm as reversing our entire buffer):
// walk again, reversing each word.
i = 0;
while (sentence[i])
{
// skip ws; root 'i' at beginning of word
while (sentence[i] == ' ') // or use std::isspace(sentence[i])
++i;
// skip until ws or eos; root 'j' at one-past end of word
j = i;
while (sentence[j] && sentence[j] != ' ') // or use !std::isspace(sentence[j])
++j;
// remember the last position
size_t last = j;
// same reversal algorithm we had before
while (i < j--)
{
char c = sentence[i];
sentence[i++] = sentence[j];
sentence[j] = c;
}
// start at the termination point where we last stopped
i = last;
}
Putting It All Together
Though considerably simpler to use pointers than all these index variables, the following will do what you're attempting, in place.
#include <iostream>
int main()
{
char s[] = "dogs like cats";
std::cout << s << '\n';
size_t len = 0, i, j;
while (s[len])
++len;
// reverse entire sequence
i = 0, j = len;
while (i < j--)
{
char c = s[i]; // or use std::swap
s[i++] = s[j];
s[j] = c;
}
// walk again, reversing each word.
i = 0;
while (s[i])
{
// skip ws; root 'i' at beginning of word
while (s[i] == ' ') // or use std::isspace
++i;
// skip until ws or eos; root 'j' at one-past end of word
j = i;
while (s[j] && s[j] != ' ') // or use !std::isspace
++j;
// remember the last position
size_t last = j;
while (i < j--)
{
char c = s[i]; // or use std::swap
s[i++] = s[j];
s[j] = c;
}
// start at last-left posiion
i = last;
}
std::cout << s << '\n';
return 0;
}
Output
dogs like cats
cats like dogs
My advise would be to break up the original string into an array of words, reverse that array. Then add those words to your reversed sentence with a space in between.
Since they asked for no libraries, I assumed no std::string, no vectors, nothing at all and so I wrote it in C.. the only thing used is printf. Everything else is from scratch :l
The idea is that you reverse the array first. Then split the array by space and reverse each word.
Example: http://ideone.com/io6Bh9
Code:
#include <stdio.h>
int strlen(const char* s)
{
int l = 0;
while (*s++) ++l;
return l;
}
void reverse(char* str)
{
int i = 0, j = strlen(str) - 1;
for(; i < j; ++i, --j)
{
str[i] ^= str[j];
str[j] ^= str[i];
str[i] ^= str[j];
}
}
void nulltok(char* str, char tok, int* parts)
{
int i = 0, len = strlen(str);
*parts = 1;
for (; i < len; ++i)
{
if (str[i] == tok)
{
str[i] = '\0';
++(*parts);
}
}
}
char* reverse_sentence(char* str)
{
char* tmp = str;
reverse(str);
int i = 0, parts = 0, len = strlen(str);
nulltok(str, 0x20, &parts);
while(parts--)
{
reverse(str);
str += strlen(str) + 1;
}
for(; i < len; ++i)
if (tmp[i] == '\0')
tmp[i] = 0x20;
return tmp;
}
int main(void)
{
char str[] = "dogs like cats";
printf("%s", reverse_sentence(str));
return 0;
}
My solution
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string str;
cout<<"enter the sentence"<<endl;
getline(cin,str);
char* pch;
pch = strtok((char*)str.c_str()," ");
string rev = "";
while(NULL != pch)
{
rev.insert(0,pch);
rev.insert(0," ");
pch = strtok(NULL," ");
}
cout<<"the reversed string is :"<<rev<<endl;
return 0;
}