replacing space with %20 - c++

The following program replaces all spaces with %20.the compilation works fine but the program terminates during the runtime.Any help???
#include<iostream>
#include<string>
using namespace std;
void removeSpaces(string url){
int len=url.length();
int i,count=0;
while(i<=len){
if(url[i]==' ')
count++;
i++;
}
int length2=len+(count*2);
string newarr[length2];
for(int j=len-1;j>=0;j--){
if(url[j]==' ')
{
newarr[length2-1]='0';
newarr[length2-2]='2';
newarr[length2-3]='%';
length2=length2-3;
}
else
{
newarr[length2-1]=url[j];
length2=length2-1;
}
}
cout<<"\nThe number of spaces in the url is:"<<count;
cout<<"\nThe replaced url is:"<<newarr;
}
int main(){
string url="http://www.ya h o o.com/";
removeSpaces(url);
}

This is called an "off by one" error.
while(i<=len){
if(url[i]==' ')
I'd also look at std::string::find() and std::string::replace() rather than what you're doing.
EDIT: Since the poster has said this isn't homework:
for (size_t pos = myString.find(' ');
pos != string::npos;
pos = myString.find(' ', pos))
{
myString.replace(pos, 1, "%20");
}

i is not initialized to 0 - this is the danger if using ',' instead of putting each variable on its own line.

As long as you're using string and not char *, why not use the string methods? This is essentially a translation of what you're trying to do (without even using ::find or ::replace):
void removeSpaces(string url)
{
string newUrl;
int count = 0;
for (int j = 0; j < url.length(); ++j)
{
if (url.at(j) == ' ')
{
newUrl.append("%20");
++count;
}
else
newUrl.append(url.at(j));
}
cout << "\nThe number of spaces in the url is:" << count;
cout << "\nThe replaced url is:"<< newUrl;
}
Edit: I see that #Bryan has given the version with ::find and ::replace.

string newarr[length2];
should be:
string newarr;
or
char newarr[length2];
or the more proper way:
char *newarr = new char[length2];
... // code.
delete[] newarr;

string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
size_t position = 0;
for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
{
str.replace(position ,1, toreplace);
}
return(str);
}
use it:
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");

Related

how to split a sentence into strings using recursion in c++

string strings[10];
void split(string s){
int curr=0,start=0,end=0,i=0;
while(i<=len(s)){
if(s[i]==' ' or i == len(s)){
end = i;
string sub;
sub.append(s,start,end-start);
strings[curr] = sub;
start = end + 1;
curr += 1 ;
}
i++;
}
}
for example if the input is " computer laptop screen desktop mouse " then the output string should be:
computer
laptop
screen
desktop
mouse
I have successfully tried using loops but failed using recursion,
can anyone help me solve split() using recursion.
Thank you
This solution assumes you want only words from the string to enter your array and that you want to split on some predetermined string delimiter like <space>" " or <double-dash>"--".
If you need to keep the void function signature, here is one:
void split_rec(string str_array[], size_t arr_index,
string s, string delimiter) {
if (s == "") {
return;
}
size_t str_index = s.find(delimiter);
string word = s.substr(0, str_index);
if (word != "") {
str_array[arr_index++] = word;
}
// find type functions return string::npos if they don't find.
str_index = s.find_first_not_of(delimiter, str_index);
if (str_index == string::npos) {
return;
}
return split_rec(str_array, arr_index, s.substr(str_index), delimiter);
}
But I would recommend returning the size of the array so you communicate what the function is doing more accurately. Like this:
size_t split_rec(string str_array[], size_t arr_index,
string s, string delimiter) {
if (s == "") {
return arr_index;
}
size_t str_index = s.find(delimiter);
string word = s.substr(0, str_index);
if (word != "") {
str_array[arr_index++] = word;
}
str_index = s.find_first_not_of(delimiter, str_index);
if (str_index == string::npos) {
return arr_index;
}
return split_rec(str_array, arr_index, s.substr(str_index), delimiter);
}
Then the call is like this:
string strings[10];
// I left some extra spaces in this string.
string str = " computer laptop screen desktop mouse ";
size_t strings_len = split_rec(strings, 0, str, " ");
cout << "Array is length " << strings_len << endl;
for (size_t i = 0; i < strings_len; i++) {
cout << strings[i] << endl;
}
Array is length 5
computer
laptop
screen
desktop
mouse

Adding Space to String at certain places in C++

I am having trouble figuring out the process to add a space in a string at capital letters in C++. If I have a string "HelloWorld", how do I convert that to "Hello World"?
I've tried using substrings and the isupper function but I can't get anything to work.
Edit: this is the code I have. I don't understand why in = newname is not valid code.
string breakStringAtCaps(string in) {
string newname[10];
int j = 0;
for (int i = 0; i < in.size(); i++) {
if (isupper(in[i]) && i != 0) {
newname[j] = " ";
j++;
}
newname[j] = in[i];
j++;
}
in = newname;
return in;
}
You can do it like this:
string breakStringAtCaps(const string& in)
{
string newname;
for(int i = 0; i < in.size(); i++)
{
if(isupper(in[i]) && i != 0)
newname += " ";
newname += in[i];
}
return newname;
}
You are thinking right in thinking substr, but you implementation is a bit off. If creating an new string containing the contents of the original and inserting a ' ' (space) before each upper-case letter (not including the first), you can seed the new string with the first character of the original using substr(0,1) and then use an auto ranged for loop and substr(1) to evaluate each character after the first.
The loop along with a check of isupper() is basically all you need, e.g.
#include <iostream>
#include <string>
#include <cctype>
int main (int argc, char **argv) {
std::string s = argc > 1 ? argv[1] : "HelloWorld",
snew = s.substr (0,1);
if (s.size() > 0)
for (auto& c : s.substr(1)) {
if (std::isupper (c))
snew += " ";
snew += c;
}
std::cout << snew << '\n';
}
(the program will use "HelloWorld" by default if no string is given as an argument on the command line, otherwise the string given on the command line is used)
Example Use/Output
$ ./bin/spacebeforeupper
Hello World
Or with a string given as an argument:
$ ./bin/spacebeforeupper MyDogHasFleas
My Dog Has Fleas
You can iterate through the strin characters, check if it is a cap and insert a ' ' before if it is one:
It should look like:
for(int i=0; i < str.length(); i++)
{
if (str[i]>='A' && str[i]<='Z')
{
if (i != 0)
cout << " ";
cout << str[i];
}
else
{
cout << str[i];
}
}
I just give a implementation, maybe not the best solution:
#include <string>
#include <ctype.h>
void breakStringAtCaps(std::string& in) {
std::string::const_iterator it = in.begin();
while(it != in.end()) {
if(it != in.begin() && isupper(*it)) {
in.insert(it, ' ');
it += 2;
}
else
++it;
}
}
//
#include <iostream>
int main(int argc, char** argv) {
std::string str("HelloWorld;");
breakStringAtCaps(str);
std::cout << str.c_str() << std::endl;
return 0;
}
and in your code,
string newname[10];
here 'newname' is a string array's name. you should not assign the name of array to a string instance.
and newname[i] means the i-th string of the array, not the i-th char of a string named 'newname' as you desired.

How to replace "ta" in a string "potato" in c++? 2 characters for 1

Here is the code:
string msg;
niceArray = txtReader("chatTest/replaces.txt");
vector<vector<string>>vMaster;
if(vMaster.size() <1){
string arr[] = { "a","A","á","#","à","â","ã","ÃÃ","€Ã","ƒÃ"};
vector<string> tempA(arr, arr+4);
vMaster.push_back(tempA);//"aAá#àâãÃÀÃÂ"
}
string ex;
while(sstr.good()){
sstr>>ex;
vectorCheck.push_back(ex);
}
for(int e = 0; e < vectorCheck.size(); e=e+1){
//if(e > vectorCheck[e].length()) break;
auto str = vectorCheck[e];
for(int b = 0; b < vMaster.size(); b=b+1){
for(int j=0; vMaster[b].size(); j=j+1){
//int f = str.find(vMaster[b][j]);
if(str.find(vMaster[b][j]) != std::string::npos){
int f = str.find(vMaster[b][j]);
//if(vMaster[b][j].length() > 1){
str.replace(f,2,vMaster[b][0]);
//break;
// }
//
}
}
}
for(int i = 0; i < xingArray.size(); i=i+1){
if(str == xingArray[i]){
vectorCheck[e] = niceArray[rand() % niceArray.size()];
}
}
}
So for each sentence i type i am checking each word and looking if there is any of that string arr characteres in it, if there is i replace it for the vector[0] in this case "a".
The problem is that this line str.find(vMaster[b][j]) != std::string::npos never returns me -1... Even when i type like "c" in finds c in there or "f" or any word and i get an error. The funny stuff is that when i type like "á" that turns into "Ã|" it works and with the "ã" that turns into "ã" it doesnt give me 0 again... I really dont know whats going on... I really tried hard here and if anyone has any opinion i would like to hear thanks.
std::string str ("potato.");
std::string str2 ("ta");
std::size_t found = str.find(str2);
if ( found != std::string::npos)
std::cout << "first 'ta' found at: " << found << '\n';
str.replace( found, 2, "");
I dont think C++ has any single method to find and replace so why not use inbuilt find and then replace.
For example:
void find_and_replace(string& source, string const& find, string const& replace)
{
for(std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
{
source.replace(i, find.length(), replace);
i += replace.length() - find.length() + 1;
}
}
int main()
{
string text = "potato";
find_and_replace(text, "ta", "");
cout << "After one replacement: " << text << endl;
find_and_replace(text, "te", "");
cout << "After another replacement: " << text << endl;
return 0;
}

C++ find special char and move to the end of a string

I am currently a student taking C++. My issue is that my nested if statement does not find the special chars if they are at the end of the word. From what I can tell, it does not run the function at all. If anyone has any idea what is wrong that will be great!
#include <iostream>
#include <string>
using namespace std;
bool isVowel(char ch);
string rotate(string pStr);
string pigLatinString(string pStr);
bool specialChar(char ch);
int main() {
string str, str2, pigsentence, finalsentence, orgstr, end;
int counter, length, lengtho;
counter = 1;
cout << "Enter a string: ";
getline (cin, str);
cout << endl;
orgstr = str;
//Add in option to move special chars
string::size_type space;
do {
space = str.find(' ', 0); //Finds the space(s)
if(space != string::npos){
str2 = str.substr(0, space); //Finds the word
if(specialChar(str[true])) { //Finds special char
end = str.substr(space - 1); //Stores special char as end
cout << end << endl; //Testing end
str.erase(space - 1); //Erases special car
}
str.erase(0, space + 1); //Erases the word plus the space
pigsentence = pigLatinString(str2); //converst the word
finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
}else {
length = str.length();
str2 = str.substr(0, length); //Finds the word
if(specialChar(str[true])) { //Finds special char
end = str.substr(space - 1); //Stores special char as end
cout << end << endl; //Testing end
str.erase(space - 1); //Erases special car
}
str.erase(0, length); //Erases the word
pigsentence = pigLatinString(str2); //converst the word
finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
counter = 0;
}
}while(counter != 0); //Loops until counter == 0
cout << "The pig Laten form of " << orgstr << " is: " << finalsentence << endl;
return 0;
}
The function that lists the specialChars is below
bool specialChar(char ch) {
switch(ch) {
case ',':
case ':':
case ';':
case '.':
case '?':
case '!':
return true;
default:
return false;
}
}
I do have other functions but they are working and just convert a word to piglatin.
your isSpecialChar takes a character as argument so str[index] would be something you could pass but instead you write str[true] which is not correct. If you want to check if there is a specialChar in your string you need to loop through the whole string and check each character.
It seems as if you want to split up a string into words so you could write something like this
char Seperator = ' ';
std::istringstream StrStream(str);
std::string Token;
std::vector<std::string> tokens;
while(std::getline(StrStream, Token, Seperator))
{
tokens.push_back(Token);
}
now that you have the words in a vector you can do whatever what you want
with them like checking for a special char
for (int i = 0; i < tokens.size(); ++i)
{
std::string& s = tokens[i];
for (int j = 0; j < s.length(); ++j)
{
if ( specialChar( s[j] )
{
...do whatever...
}
}
}
You're using true as your array index when passing arguments to the specialChar() function! Surely that isn't what you meant to do. Fix that and you might see some improvement.
Think of the function call broken down a little, like this, to help you keep track of the types:
// takes a char, returns a bool, so....
bool specialChar( char in )
{ ... }
for( int i = 0; i < str.size(); i++ )
{
char aChar = str[i];
// ...pass in a char, and receive a bool!
bool isSpecial = specialChar(aChar);
if( isSpecial )
{
...
}
}
There's generally no harm in writing the code in a way that makes it clearer to you what's going on, when compiled and optimised it will all likely be the same.

Removal of special character in string in C++

I have the followoing
string myStr = "myname-abc";
string myStr1 = strstr(myStr.c_str(), "-");
now in myStr1 i have -abc. But i don't want "-" infront of it i want to have "abc" how do i do that using string data type.
Thanks for help.
Not sure if I'm following, but you want to erase the first element?
str.erase(0, 1); // erases 1 element starting from position 0
Also, if you just want to erase everything up to -:
str.erase(0, str.find('-') + 1);
If the data you are feeding the program isn't guaranteed to have a - somewhere, you should check the return value of str.find('-') for string::npos, the return value when no occurence is found.
string myStr1 = strstr(mStr.c_str(), "-") + 1;
or if you want to avoid converting to C style strings:
string myStr1(m_Str, m_Str.find('-') + 1);
size_t pos = myStr.find('-');
if (pos != std::string::npos)
{
myStr1 = myStr.substr(pos + 1);
}
This program outputs
abc abc
int main()
{
string myStr = "myname-abc";
string myStr1 = strstr(myStr.c_str(), "abc");
int index = 0;
while(myStr[index++] != '-'){}
string myStr2 = myStr.substr(index);
cout << myStr1 << " " << myStr2 << endl;
return 0;
}
std::string myStr("myname-abc");
std::string myStr1(++std::find(myStr.begin(), myStr.end(), '-'),
myStr.end());
If I understand what you are asking for, it's to remove instance of "-" from the string? If so, the following will also work..
string foo("-abc");
string::size_type fm = foo.find('-');
while (fm != string::npos)
{
foo.erase(foo.begin() + fm);
fm = foo.find('-', fm); // find the next instance of "-"
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char a[30];
cout<<"enter any string ";
cin.get(a,30);
char b[30];
for(int i=0;a[i]!='\0';i++)
{
if(a[i]!='!' && a[i]!='#'&& a[i]!='#' && a[i]!='$' && a[i]!='%' && a[i]!='^' && a[i]!='&' && a[i]!='*' && a[i]!='?')
{
b[i]=a[i];
cout<<b[i];
} }
getch();
}