Parse string and swap substrings [closed] - c++

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

Related

How to match a string to regex based on a certain index? [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 3 years ago.
Improve this question
I am working on a small project of mine, and I need to match a string to a regex value, and the first character of the match needs to start exactly at a certain index.
I need to do this in C++, but can't find a method or function that seems like it would work on cplusplus.com.
Eg. if I put in the string Stack overflow into the pattern f.ow
and an index of 3, it should return false. But if I set the index to 10, it should return true and allow me to find out what actually matched (flow). And if I put in an index of 11, it should also return false.
Try this function, hope this will work for you
#include<iostream>
#include<regex>
#include<string.h>
using namespace std;
bool exactRegexMatch(string str,int index){
regex reg("f(.)ow");
return regex_match(str.substr(index), reg);
}
int main(){
if(exactRegexMatch("Stack Overflow",10)){
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}
}
How to match a string to regex based on a certain index?
Pass the substring starting from the index as the string argument, and add ^ to the beginning of the regex so that it only matches when the pattern starts from the beginning of the substring.
This uses the whole string by constructing the regex.
strRx = `"^[\\S\\s]{" + strOffset + "}(f.ow)";
// make a regex out of strRx
or, use iterators to jump to the location to start matching from
bool FindInString( std::string& sOut, std::string& sInSrc, int offset )
{
static std::regex Rx("(f.ow)");
sOut = "";
bool bRet = false;
std::smatch _M;
std::string::const_iterator _Mstart = sInSrc.begin() + offset;
std::string::const_iterator _Mend = sInSrc.end();
if ( regex_search( _Mstart, _Mend, _M, Rx ) )
{
// Check that it matched at exactly the _Mstart position
if ( _M[1].first == _Mstart )
{
sOut = std::string(_M[1].first, _M[1].second);
bRet = true;
}
}
return bRet;
}

What is the most efficient C++ method to split a string based on a particular delimiter similar to split method in python? [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 8 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
getline(cin,s);
istringstream iss(s);
do
{
string sub;
iss>>sub;
q.insert(sub);
}while(iss);
I used this technique when question wanted me to split on the basis of space so can anyone explain me how to split when there's a particular delimiter like ';' or ':'.
Someone told me about strtok function but i am not able to get it's usage so it would be nice if someone could help.
First, don't use strtok. Ever.
There's not really a function for this in the standard library.
I use something like:
std::vector<std::string>
split( std::string const& original, char separator )
{
std::vector<std::string> results;
std::string::const_iterator start = original.begin();
std::string::const_iterator end = original.end();
std::string::const_iterator next = std::find( start, end, separator );
while ( next != end ) {
results.push_back( std::string( start, next ) );
start = next + 1;
next = std::find( start, end, separator );
}
results.push_back( std::string( start, next ) );
return results;
}
I believe Boost has a number of such functions. (I implemented
most of mine long before there was Boost.)

Removing a subtring from a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a string which represents a file name, and I want to remove the extension, so erasing everything after the ".". What would be the best way ? Thanks.
Below code can be used for the same..
int npos = str.find_last_of('.');
str = str.substring(0,npos);
If you're on Windows, the following function will do the trick:
std::wstring StripFileExtension(std::wstring fileName)
{
WCHAR tempBuffer[MAX_PATH];
if (fileName.empty())
{
return TEXT("");
}
wcscpy(tempBuffer, fileName.c_str());
PathRemoveExtension(tempBuffer);
return tempBuffer;
}
you can use std::string , and copy each character to new string
std::string name = "filename.jpg", newname ="";
int thelength = 0;
for(int i=name.length();i>0;i--){
if( name[i] != '.'){
thelength++;
}
else{
break;
}
}
for(int i=0;i<(name.length()-thelength);i++){
newname+=name[i];
}

How can I replace percent sign (%) with two %'s? [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 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();
}
}

How to use regex 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 have a string like below:
std::string myString = "This is string\r\nIKO\r\n. I don't exp\r\nO091\r\nect some characters.";
Now I want to get rid of the characters between \r\n including \r\n.
So the string must look like below:
std::string myString = "This is string. I don't expect some characters.";
I am not sure, how many \r\n's going to appear.
And I have no idea what characters are coming between \r\n.
How could I use regex in this string?
Personally, I'd do a simple loop with find. I don't see how using regular expressions helps much with this task. Something along these lines:
string final;
size_t cur = 0;
for (;;) {
size_t pos = myString.find("\r\n", cur);
final.append(myString, cur, pos - cur);
if (pos == string::npos) {
break;
}
pos = myString.find("\r\n", pos + 2);
if (pos == string::npos) {
// Odd number of delimiters; handle as needed.
break;
}
cur = pos + 2;
}
Regular expressions are "greedy" by default in most regex libaries.
Just make your regex say "\r\n.*\r\n" and you should be fine.
EDIT
Then split your input using the given regex. That should yield two strings you can combine into the desired result.