C string handling function to get substring [closed] - c++

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.
Improve this question
I remenber a function in C or C++ that can do something like this:
string = "Hello my name is: 1234567 have a good day!"
function(string, "Hello my name is: %s have a good day!", substring)
and substring would be 1234567. What function is that?

In C, you can do that with sscanf(). Of course, there is no string datatype in C, though:
#include <stdio.h>
int main(void)
{
const char string[] = "Hello my name is: 1234567 have a good day!";
char substring[32];
if(sscanf(string, "Hello my name is: %31s have a good day!", substring) == 1)
{
printf("got '%s'\n", substring);
}
return 0;
}

sscanf is the function that you search.

It seems like you are trying to extract the number and not really so much the substring.
If your prefix string always begins with the format: "Hello my name is: " You can do:
const auto size = strlen("Hello my name is: ");
int substring = stoi(string.substr(size));
If you are unsure of your prefix, then I'd recommend a regex:
smatch m;
regex_search(string, m, regex(".*?(-?\\d+)"));
int substring = stoi(m[1]);

You may be looking for sscanf, but you probably want C++ regular expressions.
Start with a std::regex:
std::regex re( "Hello my name is: \b(\w+)\b have a good day!" );
Then put it into a function:
std::string get_name( std::string const& src ) {
static std::regex re( R"-(Hello my name is: (\w+) have a good day!)-" );
std::smatch results;
bool bworked = std::regex_match( src, results, re );
if (!bworked) return {};
// Assert(results.size() >= 2);
if (results.size() < 2) return {};
return results.str(1);
}
This gives you a lot more control than sscanf with only a bit more work.
live example
Going beyond regular expressions reaches full on parsing.
This solution uses C++11 features. Some compilers have <regex> headers that are basically stubs as well, so check compiler support.

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

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

C++ How to Extract Substring between two same symbols [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 6 years ago.
Improve this question
I am new to c++ programming. I need some help,
I have string :
---- Input : "Name : $$ Enter Your Name2 $$"
I want to extract string between $$ symbols including symbols :
---- Output : "$$ Enter Your Name2 $$"
Please help me.
Regular Expression are very useful in this case.
C++11 has regex library.
#include <string>
#include <regex>
std::string parse_string(const std::string& str) {
static const std::string REGEX_STR = R"__(\$\$(\w|\W)*\$\$)__";
std::regex regex(REGEX_STR);
std::smatch regex_iterator;
if (std::regex_search(str, regex_iterator, regex)) {
return regex_iterator.str();
}
return std::string("");
}
The code can be improved but it should represent a good starting point. Specific case should be handled, for example: more $$*$$ in a string, etc...
Note:
R"__(\$\$(\w|\W)*\$\$)__"; is a raw string in order to make more readable the regex.
Just search the string for the delimiter:
std::string parse_string(const std::string& str, const std::string& delim) {
auto start = str.find(delim);
if (start == std::string::npos)
return "";
auto end = str.find(delim, start + delim.size());
if (end == std::string::npos)
return str.substr(start);
else
return str.substr(start, end - start + delim.size);
}

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

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