How to delete plain "\n" from a string in C++? [duplicate] - c++

This question already has answers here:
How to remove all substrings from a string
(5 answers)
Closed 4 years ago.
As above, I'm trying to delete two character sub-string (not new-line character, just plain text) from a line.
What I am doing right now is line.replace(line.find("\\n"), 3, ""); because I wanted to escape it, but I receive debug error saying that abort() has been called. Moreover, I am not sure about size 3, because first slash shouldn't be treated as a literal character.

I guess this is exactly what you're looking for:
std::string str = "This is \\n a string \\n containing \\n a lot of \\n stuff.";
const std::string to_erase = "\\n";
// Search for the substring in string
std::size_t pos = str.find(to_erase);
while (pos != std::string::npos) {
// If found then erase it from string
str.erase(pos, to_erase.length());
pos = str.find(to_erase);
}
Note that you're likely getting std::abort because you are passing std::string::npos or the length 3 (not 2) to std::string::replace.

#include <iostream>
#include <string>
int main()
{
std::string head = "Hi //nEveryone. //nLets //nsee //nif //nthis //nworks";
std::string sub = "//n";
std::string::iterator itr;
for (itr = head.begin (); itr != head.end (); itr++)
{
std::size_t found = head.find (sub);
if (found != std::string::npos)
head.replace (found, sub.length (), "");
}
std::cout << "after everything = " << head << std::endl;
}
i got the output as :
after everything = Hi Everyone. Lets see if this works

Related

Getting a word or sub string from main string when char '\' from RHS is found and then erase rest

Suppose i have a string as below
input = " \\PATH\MYFILES This is my sting "
output = MYFILES
from RHS when first char '\' is found get the word (ie MYFILES) and erase the rest.
Below is my approach i tired but its bad because there is a Runtime error as ABORTED TERMINATED WITH A CORE.
Please suggest cleanest and/or shortest way to get only a single word (ie MYFILES ) from the above string?
I have searching and try it from last two days but no luck .please help
Note: The input string in above example is not hardcoded as it ought to be .The string contain changes dynamically but char '\' available for sure.
std::regex const r{R"~(.*[^\\]\\([^\\])+).*)~"} ;
std::string s(R"(" //PATH//MYFILES This is my sting "));
std::smatch m;
int main()
{
if(std::regex_match(s,m,r))
{
std::cout<<m[1]<<endl;
}
}
}
To erase the part of a string, you have to find where is that part begins and ends. Finding somethig inside an std::string is very easy because the class have six buit-in methods for this (std::string::find_first_of, std::string::find_last_of, etc.). Here is a small example of how your problem can be solved:
#include <iostream>
#include <string>
int main() {
std::string input { " \\PATH\\MYFILES This is my sting " };
auto pos = input.find_last_of('\\');
if(pos != std::string::npos) {
input.erase(0, pos + 1);
pos = input.find_first_of(' ');
if(pos != std::string::npos)
input.erase(pos);
}
std::cout << input << std::endl;
}
Note: watch out for escape sequences, a single backslash is written as "\\" inside a string literal.

Remove spaces before the first word in string in C++ [duplicate]

This question already has answers here:
Removing leading and trailing spaces from a string
(26 answers)
Closed 5 years ago.
I know how to remove one or many spaces before the first word in a string in C, but I don't know in C++ (if there is a function by example).
My string is : " Hello" and I want to get "Hello". How can I do ?
Use std::string::find_first_not_of(' ') to get the index of the first non-whitespace character, then take the substring from there
Example:
std::string str = " Hello";
auto pos = str.find_first_not_of(' ');
auto Trimmed = str.substr(pos != std::string::npos ? pos : 0);
std::string TrimLeft(const std::string& str){
auto pos = str.find_first_not_of(' ');
return str.substr(pos != std::string::npos ? pos : 0);
}

Strtok and Char* [duplicate]

This question already has answers here:
C's strtok() and read only string literals
(5 answers)
Closed 8 years ago.
I have a simple code where Iam trying to go through a char* and spit it into separate words. Here is the simple code I have.
#include <iostream>
#include <stdio.h>
int main ()
{
char * string1 = "- This is a test string";
char * character_pointer;
std::cout << "Splitting stringinto tokens:" << string1 << std::endl;
character_pointer = strtok (string1," ");
while (character_pointer != NULL)
{
printf ("%s\n", character_pointer);
character_pointer = strtok (NULL, " ");
}
return 0;
}
I am getting an error that will not allow me to do this.
So my question is, how do I go through and find each word in a char*. For my actual program I am working on, one of my libraries returns a paragraph of words as a const char* and I need to stem each word using a stemming algorithm (I know how to do this, I just do not know how to send each individual word to the stemmer). If someone could just solve how to get the example code to work, I will be able to figure it out. All of the examples online use a char[] for string1 instead of a char* and I cannot do that.
This is the simplest (codewise) way I know to split a string in c++:
std::string string1 = "- This is a test string";
std::string word;
std::istringstream iss(string1);
// by default this splits on any whitespace
while(iss >> word) {
std::cout << word << '\n';
}
or like this if you want to specify a delimiter.
while(std::getline(iss, word, ' ')) {
std::cout << word << '\n';
}
Here's a corrected version, try it out:
#include <iostream>
#include <stdio.h>
#include <cstring>
int main ()
{
char string1[] = "- This is a test string";
char * character_pointer;
std::cout << "Splitting stringinto tokens:" << string1 << std::endl;
character_pointer = strtok (string1," ");
while (character_pointer != NULL)
{
printf ("%s\n", character_pointer);
character_pointer = strtok (NULL, " ");
}
return 0;
}
There are different ways you could do this in C++.
If space is your delimited then you can get the tokens this way:
std::string text = "- This is a test string";
std::istringstream ss(text);
std::vector<std::string> tokens;
std::copy(std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string>>(tokens));
You can also tokenize the string in C++ using regular expressions.
std::string text = "- This is a test string";
std::regex pattern("\\s+");
std::sregex_token_iterator it(std::begin(text), std::end(text), pattern, -1);
std::sregex_token_iterator end;
for(; it != end; ++it)
{
std::cout << it->str() << std::endl;
}
Forget about strtok. To get exactly what you seem to be
aiming for:
std::string const source = "- This is a test string";
std::vector<std::string> tokens;
std::string::const_iterator start = source.begin();
std::string::const_iterator end = source.end();
std::string::const_iterator next = std::find( start, end, ' ' );
while ( next != end ) {
tokens.push_back( std::string( start, next ) );
start = next + 1;
next = std::find( start, end, ' ' );
}
tokens.push_back( std::string( start, next ) );
Of course, this can be modified as much as you want: you can use
std::find_first_of is you want more than one separator, or
std::search if you want a multi-character separator, or even
std::find_if for an arbitrary test (with a lambda, if you have
C++11). And in most of the cases where you're parsing, you can
just pass around two iterators, rather than having to construct
a substring; you only need to construct a substring when you
want to save the extracted token somewhere.
Once you get used to using iterators and the standard
algorithms, you'll find it a lot more flexible than strtok,
and it doesn't have all of the drawbacks which the internal
state implies.

Splitting a string using a single delimeter [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Splitting a string in C++
I'm trying to split a single string object with a delimeter into separate strings and then output individual strings.
e.g The input string is firstname,lastname-age-occupation-telephone
The '-' character is the delimeter and I need to output them separately using the string class functions only.
What would be the best way to do this? I'm having a hard time understanding .find . substr and similar functions.
Thanks!
I think string streams and getline make for easy-to-read code:
#include <string>
#include <sstream>
#include <iostream>
std::string s = "firstname,lastname-age-occupation-telephone";
std::istringstream iss(s);
for (std::string item; std::getline(iss, item, '-'); )
{
std::cout << "Found token: " << item << std::endl;
}
Here's using only string member functions:
for (std::string::size_type pos, cur = 0;
(pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos)
{
std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl;
if (pos != s.npos) ++pos; // gobble up the delimiter
}
I'd do something like this
do
{
std::string::size_type posEnd = myString.find(delim);
//your first token is [0, posEnd). Do whatever you want with it.
//e.g. if you want to get it as a string, use
//myString.substr(0, posEnd - pos);
myString = substr(posEnd);
}while(posEnd != std::string::npos);

c++ ignore front spaces when comparing strings eg: "str1"compare.(" str2") = TRUE [duplicate]

This question already has answers here:
Removing leading and trailing spaces from a string
(26 answers)
Closed 7 years ago.
Hi I was wondering what is the shortest way to make string str1 seem equal to string str2
str1 = "Front Space";
str2 = " Front Space";
/*Here is where I'm missing some code to make the strings equal*/
if (str1.compare(str2) == 0) { // They match
cout << "success!!!!" << endl; // This is the output I want
}
All I need it for str1 to equal str2
How can I do it?
I have made multiple attempts but they all don't seem to work correctly. I think it's because of the number of characters in the string, ie: str1 has less characters than str2.
for (int i = 1; i <= str1.length() + 1; i++){
str1[str1.length() - i ] = str1[str1.length() - (i + 1)];
}
Any help appreciated
If you can use Boost, trim functions are available in boost/algorithm/string.hpp
str1 = "Front Space";
str2 = " Front Space";
boost::trim_left( str2 ); // removes leading whitespace
if( str1 == str2 ) {
// ...
}
Similarly, there's trim that removes both leading and trailing whitespace. And all these functions have *_copy counterparts that return a trimmed string instead of modifying the original.
If you cannot use Boost, it's not hard to create your own trim_left function.
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
void trim_left( std::string& s )
{
auto it = s.begin(), ite = s.end();
while( ( it != ite ) && std::isspace( *it ) ) {
++it;
}
s.erase( s.begin(), it );
}
int main()
{
std::string s1( "Hello, World" ), s2( " \n\tHello, World" );
trim_left( s1 ); trim_left( s2 );
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
}
Output:
Hello, World
Hello, World
As others have said, you can use boost. If you don't want to use boost, or you can't (maybe because it's homework), it is easy to make an ltrim function.
string ltrim(string str)
{
string new_str;
size_t index = 0;
while (index < str.size())
{
if (isspace(str[index]))
index++;
else
break;
}
if (index < str.size())
new_str = str.substr(index);
return new_str;
}
LLVM also has some trim member functions for their StringRef class. This works without modifying your string and without making copies, in case that's important to you.
llvm::StringRef ref1(str1), ref2(str2);
ref1.ltrim();
ref2.ltrim();
if (ref1 == ref2) {
// match
}