How can I replace percent sign (%) with two %'s? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to try replace a percentage sign in a char array with two %% signs. Because a % sign causes problems, if I write as output char array. Therefore percentage sign must be replaced with two %% signs without using string.
// This array causes dump because of '%'
char input[] = "This is a Text with % Charakter";
//Therefore Percent Sign(%) must be replaced with two %%.

You can use an std::string to handle the necessary memory re-allocations for you, plus a boost algorithm to make everything easier:
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
std::string input("This is a Text with % Charakter and another % Charakter");
boost::replace_all(input, "%", "%%");
std::cout << input << std::endl;
}
Output:
This is a Text with %% Charakter and another %% Charakter
If you can't use boost, you can write your own version of replace_all using std::string::find and std::string::replace:
template <typename C>
void replace_all(std::basic_string<C>& in,
const C* old_cstring,
const C* new_cstring)
{
std::basic_string<C> old_string(old_cstring);
std::basic_string<C> new_string(new_cstring);
typename std::basic_string<C>::size_type pos = 0;
while((pos = in.find(old_string, pos)) != std::basic_string<C>::npos)
{
in.replace(pos, old_string.size(), new_string);
pos += new_string.size();
}
}

Related

Checking the availability of a word within a phrase, in a given position [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Please let me know how can I check whether the first word of a given string is "echo" ,ignoring if any spaces before the word.
Example:
string hello = " echo hello hihi";
if(startwith(hello, "echo")
{
//some code here
}
Please help me if possible
string_view has a similar functionality. Just skip the white space and use that.
#include <string>
#include <string_view>
using std::string, std::string_view;
constexpr bool StartsWithSkipWs(string_view const str,
string_view const prefix) noexcept {
auto begin = str.find_first_not_of(" \t\n\f\r\v");
if (begin == string_view::npos) return false;
return str.substr(begin).starts_with(prefix);
}
int main() {
string hello = "echo hello hihi";
if (StartsWithSkipWs(hello, "echo"))
{
// ...
}
}
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
int main(){
string hello = " echo hello hihi";
boost::trim_left(hello);
string subst=hello.substr(0,4);
if(subst=="echo"){
////some code here
}
}

count a specific word in string in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new at programming. please help me to solve this program :
the program gets a string and a word , and check the number of occurrences of that word in the string using c\c++.
thank you vary much
this is my first post.
If you want to find number of occurrence of a pattern or word in a string you can use KMP algorithm.
It will give you the total number of occurrences of a word in a string.
Example :
string = "abaabcabaabd"
word = "aba"
Output will be 2, abaabcabaabd
Complexity : O(n) where n is the length of the string
UPDATE 1:
I don't know actually what problem you are talking about :(
But if you want to count number of words like this example :
string : hi how are you how are hi how
word : how
how contain 3 times. hi *how* are you *how* are hi *how*
If your problem is like this, then this program will do :
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str,word;
getline(cin,str);
getline(cin,word);
stringstream ss(str);
int cnt=0;
while(ss>>str)
{
if(str==word)
cnt++;
}
cout<<cnt<<"\n";
return 0;
}
UPDATE 2:
Using pointer to solve same problem :
#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[100],word[100];
gets(str);
gets(word);
char *token=strtok(str," ");
int cnt=0;
while(token!=NULL)
{
if(strcmp(token,word)==0)
cnt++;
token=strtok(NULL," ");
}
cout<<cnt<<"\n";
return 0;
}

stopword removal in C++ code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char filename[50]; //open file
ifstream example;
cin.getline(filename , 50);
example.open(filename);
if(!example.is_open())
{
exit(EXIT_FAILURE);
}
char word[50];
example>>word;
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
{
cout <<word<<" "; // remove stopwords
example>>word;
}
system("PAUSE");
return 0;
}
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
You cannot compare C-strings with the == operator. The easiest solution to your problem will be to use std::string:
string word;
example >> word;
while (example.good() && word != "a" && word != "an" && word != "be" && word != "at" && word != "the")
{
cout << word << " "; // remove stopwords
example >> word;
}
On the other hand, this will actually not remove all, as you call it, stopwords. It will just print all words until the first “stopword” is read, and then the whole loop will stop.
The problem is that you're using C-style strings, which are fiddly to use correctly. The simplest option is to use the C++ strings library:
#include <string>
std::string word;
and the rest of your program should work as expected. This will also prevent the hideous stack-corruption bug that your program will experience if an input word is too long.
If you really want to muck around with character arrays for educational purposes, then you'll need to use the C strings library to compare them:
#include <cstring>
if (std::strcmp(word, "a") != 0 && ...)
Your code compares the address of the array containing the input word with the address of a string literal; these will never be equal.
When removing stopwords, remove not only a few of them.
In addition, you should apply the Porter algorithm to your piece of code.
The Porter Stemmer has to be applied regarding string similarity if you wanna check a filtered text.
Yes, it is in C, but only applying a few words (like your question) is not an adequate removal procedure of stopwords. The C code gives you an impression if you really wanna stem in addition to removal of stopwords. This depends on the purpose.
Have done both in 2008 to filter many text fragments. Both was relevant.
hth
A competent compiler with warnings turned on will fix your problem for you. Here's what mine said:
warning: result of comparison against a string literal is unspecified (use strncmp instead)
[-Wstring-compare]
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
^ ~~~

c++ Parsing prices of a text file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to parse the following file so it takes the item as a string then skip the # sign and then take the price as a float.
text file:
hammer#9.95
saw#20.15
shovel#35.40
how would I go about doing this?
In case when you have std::string in presented format you could use something like this:
std::string test {"test#5.23"};
std::cout << std::stof(std::string{test.begin() + test.rfind('#') + 1, test.end()});
Note that std::stof is C++11 function
Read the file line by line into a string. Find # and parse second part as float.
std::ifstream file("input.txt");
for (std::string line; std::getline(file, line); )
{
auto sharp = line.find('#'); // std::size_t sharp = ...
if (sharp != std::string::npos)
{
std::string name(line, 0, sharp);
line.erase(0, sharp+1);
float price = std::stof(line);
std::cout << name << " " << price << "\n";
}
}
Note: I didn't some error checking, do them yourself as an exercise. and also you should know about std::string, std::ifstream, std::getline and std::stof.

Parse string and swap substrings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I parse a string given by a user and swap all occurrences of the old substring with the new string. I have a function to work with but I am really uncertain when it comes to strings.
void spliceSwap( char* inputStr, const char* oldStr, const char* newStr )
The simplest solution is to use google (First link) here. Also be aware that in C++ we prefer std::string over const char *. Do not write your own std::string, use the built-in one. Your code seems to be more C than C++!
// Zammbi's variable names will help answer your question
// params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
// ASSERT(find != NULL);
// ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
// search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
// replace the found string with the replacement
source.replace( pos, findLen, replace );
// the next line keeps you from searching your replace string,
// so your could replace "hello" with "hello world"
// and not have it blow chunks.
pos += replaceLen;
}
}