Remove space chars from end of string C++ [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the best way to trim std::string
I have a string:
std::string foo = "This is a string "; // 4 spaces at end
How would I remove the spaces at the end of the string so that it is:
"This is a string" // no spaces at end
please note this is an example and not a representation of my code. I do not want to hard code:
std::string foo = "This is a string"; //wrong

Here you can find a lot of ways to trim the string.

First off, NULL chars (ASCII code 0) and whitespaces (ASCII code 32) and not the same thing.
You could use std::string::find_last_not_of to find the last non-whitespace character, and then use std::string::resize to chop off everything that comes after it.

string remove_spaces(const string &s)
{
int last = s.size() - 1;
while (last >= 0 && s[last] == ' ')
--last;
return s.substr(0, last + 1);
}

Related

Replace text \n with actual new line. (C++) [duplicate]

This question already has answers here:
How to find and replace all occurrences of a substring in a string?
(9 answers)
Replace substring with another substring C++
(18 answers)
How to find and replace string?
(11 answers)
How do I replace all instances of a string with another string?
(6 answers)
Closed 6 months ago.
I'm using C++ and I have a problem. Instead of creating a new line it prints \n. My Code:
std::string text;
std::cout << text;
It prints:Hello\nWorld
It was supposed to read \n as a new line and print something like this:
"Hello
World"
So i've tried to use replace(text.begin(), text.end(), '\n', 'a') for testing purposes and nothing happened. It contiuned to print Hello\nWorld
std::replace() won't work in this situation. When called on a std::string, it can replace only single characters, but in your case your string actually contains 2 distinct characters '\' and 'n'. So you need to use std::string::find() and std::string::replace() instead, eg:
string::size_type index = 0;
while ((index = str.find("\\n", index)) != string::npos) {
str.replace(index, 2, "\n");
++index;
}

How to replace all occurrences of a character with a given string [duplicate]

This question already has answers here:
How to replace all occurrences of a character in string?
(17 answers)
Replace part of a string with another string
(17 answers)
Closed 5 years ago.
I want to replace all occurrences of '$' with "$$". Currently I am using string::find to check if '$' is present in string or not. then I am using for loop and checking every character if it matches with '$'. If a character matches with $ then I am using string::replace to replace it.
Is there any other effective method to do this in c++? without traversing entire string with less complexity?
I don't know a standard function which replaces ALL occurrences of a certain string with another string. The replace-functions either replace all occurrences of a specific character by another character, or replace a single range of characters with another range.
So I think you cannot avoid iterating through the string on your own.
In your specific case, it might be easier, as you just have to insert an additional $ for every $-character you find. Note the special measure avoiding an endless loop, which would happen if one doubled also the $-value just inserted again and again:
int main() {
string s = "this $ should be doubled (i.e. $), then. But $$ has been doubled, too.";
auto it = s.begin();
while (it != s.end()) {
if (*it == '$') {
it = s.insert(it, '$');
it += 2;
}
else {
it++;
}
}
cout << s;
}

Allow user to pass a separator character by doubling it in C++

I have a C++ function that accepts strings in below format:
<WORD>: [VALUE]; <ANOTHER WORD>: [VALUE]; ...
This is the function:
std::wstring ExtractSubStringFromString(const std::wstring String, const std::wstring SubString) {
std::wstring S = std::wstring(String), SS = std::wstring(SubString), NS;
size_t ColonCount = NULL, SeparatorCount = NULL; WCHAR Separator = L';';
ColonCount = std::count(S.begin(), S.end(), L':');
SeparatorCount = std::count(S.begin(), S.end(), Separator);
if ((SS.find(Separator) != std::wstring::npos) || (SeparatorCount > ColonCount))
{
// SEPARATOR NEED TO BE ESCAPED, BUT DON'T KNOW TO DO THIS.
}
if (S.find(SS) != std::wstring::npos)
{
NS = S.substr(S.find(SS) + SS.length() + 1);
if (NS.find(Separator) != std::wstring::npos) { NS = NS.substr(NULL, NS.find(Separator)); }
if (NS[NS.length() - 1] == L']') { NS.pop_back(); }
return NS;
}
return L"";
}
Above function correctly outputs MANGO if I use it like:
ExtractSubStringFromString(L"[VALUE: MANGO; DATA: NOTHING]", L"VALUE")
However, if I have two escape separators in following string, I tried doubling like ;;, but I am still getting MANGO instead ;MANGO;:
ExtractSubStringFromString(L"[VALUE: ;;MANGO;;; DATA: NOTHING]", L"VALUE")
Here, value assigner is colon and separator is semicolon. I want to allow users to pass colons and semicolons to my function by doubling extra ones. Just like we escape double quotes, single quotes and many others in many scripting languages and programming languages, also in parameters in many commands of programs.
I thought hard but couldn't even think a way to do it. Can anyone please help me on this situation?
Thanks in advance.
You should search in the string for ;; and replace it with either a temporary filler char or string which can later be referenced and replaced with the value.
So basically:
1) Search through the string and replace all instances of ;; with \tempFill- It would be best to pick a combination of characters that would be highly unlikely to be in the original string.
2) Parse the string
3) Replace all instances of \tempFill with ;
Note: It would be wise to run an assert on your string to ensure that your \tempFill (or whatever you choose as the filler) is not in the original string to prevent an bug/fault/error. You could use a character such as a \n and make sure there are non in the original string.
Disclaimer:
I can almost guarantee there are cleaner and more efficient ways to do this but this is the simplest way to do it.
First as the substring does not need to be splitted I assume that it does not need to b pre-processed to filter escaped separators.
Then on the main string, the simplest way IMHO is to filter the escaped separators when you search them in the string. Pseudo code (assuming the enclosing [] have been removed):
last_index = begin_of_string
index_of_current_substring = begin_of_string
loop: search a separator starting at last index - if not found exit loop
ok: found one at ix
if char at ix+1 is a separator (meaning with have an escaped separator
remove character at ix from string by copying all characters after it one step to the left
last_index = ix+1
continue loop
else this is a true separator
search a column in [ index_of_current_substring, ix [
if not found: error incorrect string
say found at c
compare key_string with string[index_of_current_substring, c [
if equal - ok we found the key
value is string[ c+2 (skip a space after the colum), ix [
return value - search is finished
else - it is not our key, just continue searching
index_of_current_substring = ix+1
last_index = index_of_current_substring
continue loop
It should now be easy to convert that to C++

Erase all occurences of a word from a string [duplicate]

This question already has answers here:
Replace part of a string with another string
(17 answers)
Closed 7 years ago.
I have a string such as:
AAAbbbbbAAA
I'd like to remove all the occurances of a pattern AAA to get:
bbbbb
The pattern can occur anywhere in the string.
Given:
string yourstring("AAAbbbAAA");
string removestring("AAA");
You could simply run something like this multiple times on your string:
yourstring.erase(yourstring.find(removestring), removestring.length());
Of course you will have to check that string::find actually finds an occurence before using string::erase.
Here is the code. It's not very much efficient, but works well, and is a tiny code.
string h = "AAAbbbAAAB";
int pos = h.find("AAA");
while(pos!=-1)
{
h.replace(pos, 3, "");
pos = h.find("AAA");
}
cout << h << endl;
It only works if you know the pattern. If it doesn't what you want, maybe you're looking for a pattern matching algorithm, like KMP.

How to check if a string starts with ' " ' (double quotes)? [duplicate]

This question already has answers here:
Regex for quoted string with escaping quotes
(17 answers)
Closed 8 years ago.
Every time I write " my compiler assumes I am trying to write a String. Instead I want my method to tell me if the incoming string starts with a double quote ""
Ex:
String n;
if(n==n.startsWith(" " " ));
doesn't work
Any suggestions??
You have to escape double quotes in string!
If you do it like this: " " ", string ends on second quotation mark. If in Java, you code should be like:
String n;
if(n.startsWith("\""))
{
// execute if true
}
Since you are matching just first character, you don't need to use such sophisticated tool as regular expressions:
String n;
if (n.charAt(0)=="\"")
{
// execute if true
}
BUT. You should make sure if string is not empty. Just for safety:
String n;
if (n.getText()!=null
&& !n.getText().isEmpty()
&& n.charAt(0)=="\"")
{
// execute if true
}
PS: space is a character.
PSS: flagged as dublicate.