how to remove spaces from a string in C++ - c++

I used "using namespace std;" in my entire study in C++,so basically I don't understand something like std::out,please help me out.Let's say I have a code shown below,i want the two string to be the same when I compare them.
int main(void)
{
using namespace std;
char a[10] = "123 ";
char b[10] = "123";
if(strcmp(a,b)==0)
{cout << "same";}
return 0;
}

If you use std::string instead of char you could use the truncate functions from boost.

Use std::string to do it
std::string a("123 ");
std::string b("123");
a.erase(std::remove_if(a.begin(), a.end(), ::isspace), a.end());
if (a == b)
std::cout << "Same";
The difference made by using will be
using namespace std;
string a("123 ");
string b("123");
a.erase(remove_if(a.begin(), a.end(), ::isspace), a.end());
if (a == b)
cout << "Same";
It is generally advised not to use the using namespace std. Don't forget to include <string> and <algorithm>.
EDIT If you still want to do it the C way, use the function from this post
https://stackoverflow.com/a/1726321/2425366
void RemoveSpaces(char * source) {
char * i = source, * j = source;
while (*j != 0) {
*i = *j++;
if (*i != ' ') i++;
}
*i = 0;
}

use regex \\s+ to match all space characters and use regex_replace to remove it
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::string text = "Quick brown fox";
std::regex spaces("\\s+");
// construct a string holding the results
std::string result = std::regex_replace(text, spaces, "");
std::cout << '\n' << text << '\n';
std::cout << '\n' << result << '\n';
}
reference: http://en.cppreference.com/w/cpp/regex/regex_replace

Related

Reverse Word Wise using basics of C++

The question Goes like this ( my code in the last )
Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is.
Input format :
String in a single line
Output format :
Word wise reversed string in a single line
Constraints :
0 <= |S| <= 10^7
where |S| represents the length of string, S.
Sample Input 1:
Welcome to Coding Ninjas
Sample Output 1:
Ninjas Coding to Welcome
Sample Input 2:
Always indent your code
Sample Output 2:
code your indent Always
This code is in c++:
void reverseStringWordWise(char input[])
{
// Length
int count=0;
for(int i=0; input[i]!='\0'; i++)
{
count++;
}
int len=count;
//reversing the complete string
int i=0;
int j=len-1;
while(i<j)
{
char temp=input[i];
input[i]=input[j];
input[j]=temp;
i++;
j--;
}
//individual reverse
int k=0;
int a,b;
for(;k<len;)
{
for(;input[k]==' ';k++)
{
b=k-1;
break;
}
while(a<b)
{
char temp=input[a];
input[a]=input[b];
input[b]=temp;
}
}
}
can someone help me with the logic of reversing the individual word, c or c++ works.
I would get rid of the char[]s and use std::string.
Example:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <list>
void reverseStringWordWise(std::string input) {
std::list<std::string> words;
for(auto sit = input.begin();;) {
// find a space from `sit` and forward
auto eit = std::find(sit, input.end(), ' ');
// store the word first in the list
words.emplace_front(sit, eit);
if(eit == input.end()) break; // last word, break out
sit = std::next(eit); // start next search after the found space
}
// print result
for(auto& word : words) std::cout << word << ' ';
std::cout << '\n';
}
int main() {
reverseStringWordWise("Hello world");
}
Output
world Hello
If you don't want the trailing space after the last word:
void reverseStringWordWise(std::string inp) {
std::list<std::string> words;
for (auto sit = inp.begin(), eit = sit; eit != inp.end(); sit = eit + 1) {
eit = std::find(sit, inp.end(), ' ');
words.emplace_front(sit, eit);
}
if(auto it = words.begin(); it != words.end()) {
std::cout << *it;
for(++it; it != words.end(); ++it) std::cout << ' ' << *it;
}
std::cout << '\n';
}
You can use the standard library algorithms to shorten the code. If you've got start and end iterators, you can use std::reverse, you can use std::strlen to calculate the end iterator and you can use std::find to identify the next word boundary. Assuming every word seperator is a space character, this could result in the following algorithm
void reverseStringWordWise(char input[])
{
if (input[0] == '\0')
{
return;
}
auto const end = input + std::strlen(input);
std::reverse(input, end);
auto wordEnd = input;
while(true)
{
auto wordStart = wordEnd;
wordEnd = std::find(wordStart, end, ' ');
std::reverse(wordStart, wordEnd);
if (wordEnd == end)
{
break;
}
++wordEnd;
}
}
int main() {
char input1[] = "Welcome to Coding Ninjas";
char input2[] = "Always indent your code";
reverseStringWordWise(input1);
reverseStringWordWise(input2);
std::cout << input1 << '\n'
<< input2 << '\n';
}
Here is another solution, using std::stack:
#include <stack>
#include <string>
#include <sstream>
#include <iostream>
void reverseStringWordWise(std::string input)
{
std::stack<std::string> wordStack;
std::istringstream strm(input);
std::string word;
// push each word on the stack
while (strm >> word)
wordStack.push(word);
// pop stack for each word
while (!wordStack.empty())
{
std::cout << wordStack.top() << ' ';
wordStack.pop();
}
}
int main()
{
reverseStringWordWise("Welcome to Coding Ninjas");
}
Output:
Ninjas Coding to Welcome
With boost, it's easier:
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/join.hpp>
std::string reverse_words(std::string s)
{
boost::char_delimiters_separator<char> const sep(" ");
boost::tokenizer<boost::char_delimiters_separator<char>> const words(s, sep);
return boost::algorithm::join(std::reverse(words.begin(), words.end()), " ");
}
In C++, you are expected to use algorithms and not bother with rewriting everything from scratch (unless you are writing a library such as boost). Especially, as others mentioned, reading/writing to arrays directly is most often going to end up with errors (your code is missing several boundary checks).
Here is a modern C++ version. The algorithm is to reverse each word and then reverse the whole string. The code takes the string by value so it has a copy of the string and then modifies the string in-place and returns it. It uses no extra memory.
#include <iostream>
#include <string>
#include <algorithm>
std::string word_reverse(std::string s) {
auto it = s.begin();
while(it != s.end()) {
auto it2 = std::find(it, s.end(), ' ');
std::reverse(it, it2);
it = it2 + (it2 != s.end());
}
std::reverse(s.begin(), s.end());
return s;
}
int main() {
std::string s = "Always indent your code";
std::string t = word_reverse(s);
std::cout << s << std::endl;
std::cout << t << std::endl;
}
Use Regex:-
// ```c++
#include <regex>
#include <iterator>
#include <iostream>
#include <string>
using it = std::regex_iterator<std::string::const_reverse_iterator>;
int main() {
const std::string s = "Always indent your code.";
std::regex regex("[\\w]+");
for (auto i = it(s.rbegin(), s.rend(), regex); i != it(); ++i) {
auto w = i->str();
std::copy(std::rbegin(w), std::rend(w), std::ostream_iterator<char>(std::cout));
std::cout << ' ';
}
}

How can I replace multiple characters with just one (C++)?

We have a char. We need to replace all ab characters from our char with the letter c.
Example we have :
abracadabra
the output will be :
cracadcra
I tried to use replace() function from C++, but no success.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here
You can use C++11 regex:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
Problem:
That is not the syntax of std::string::replace.
Solution:
As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').
Or use regular expressions as dtell pointed.
Adittional information:
using namespace std; is considered a bad practice (More info here).
You should use std::string::size instead of strlen when you're working with std::string.
To work with std::string you should use #include <string> instead of #include <cstring>.
Full code:
#include <iostream>
int main()
{
std::string test;
std::cin >> test;
for(unsigned int i = 0; i < test.size() - 1; i++)
{
if((test[i]=='a') && (test[i+1]=='b'))
{
test.replace(i, 2, "c" );
}
}
std::cout << test << std::endl;
return 0;
}
The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra

Removing all the characters (a-z, A-Z) from a string in C++

Here's my code:
#include <iostream>
using namespace std;
string moveString(string t, int index)
{
for (int i=index; t[i]!=NULL;i++)
{
t[i]=t[i+1];
}
return t;
}
string delChars(string t)
{
for (int i=0; t[i]!=NULL; i++)
{
if (t[i]>'a' && t[i]<'z')
{
moveString(t, i);
}
else if (t[i]>'A' && t[i]<'Z')
{
moveString(t, i);
}
}
return t;
}
int main()
{
int numberOfSpaces;
string t;
cout << "Text some word: "; cin>>t;
cout<<delChars(t);
return 0;
}
First function moveString should (in theory) take down every single character from a string by 1 index down (starting from given index) - to remove 1 character. The rest is pretty obvious. But:
Input: abc123def
Output: abc123def
What am I doing wrong?
And a additional mini-question: Acutally, what's the best way to "delete" an element from an array? (array of ints, chars, etc.)
Logic Stuff is right but his answer is not enough. You shouldn't increase i after move. Since the i.th character is removed and i points to the next character now.
string delChars(string t)
{
for (int i=0; t[i]!=NULL; )
{
if (t[i]>'a' && t[i]<'z')
{
t = moveString(t, i);
}
else if (t[i]>'A' && t[i]<'Z')
{
t = moveString(t, i);
}
else
i++;
}
return t;
}
moveString takes t by value and you're not assigning its return value, so it doesn't change t in delChars. So, make sure the next thing you learn are references.
Apart from that, I don't know what to tell about t[i] != NULL (if it is undefined behavior or not), but we have std::string::size to get the length of std::string, e.g. i < t.size(). And if you havet[i + 1], the condition should then be i + 1 < t.size().
Whatever, don't play with it like with char arrays, leaving the string with previous size. You can pop_back the last (duplicate) character after shifting the characters.
It's worth mentioning that it can be done in one line of idiomatic C++ algorithms, but you want to get your code working...
What am I doing wrong?
Not using standard algorithms
Actually, what's the best way to "delete" an element from array? (array of ints, chars, etc.)
By using the standard remove-erase idiom:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstring>
int main()
{
using namespace std;
auto s = "!the 54 quick brown foxes jump over the 21 dogs."s;
cout << "before: " << quoted(s) << endl;
s.erase(std::remove_if(s.begin(),
s.end(),
[](auto c) { return std::isalpha(c); }),
s.end());
cout << "after: " << quoted(s) << endl;
return 0;
}
expected output:
before: "!the 54 quick brown foxes jump over the 21 dogs."
after: "! 54 21 ."
I'm not allowed to use standard algorithms
Then keep it simple:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstring>
std::string remove_letters(const std::string& input)
{
std::string result;
result.reserve(input.size());
for (auto c : input) {
if (!std::isalpha(c)) {
result.push_back(c);
}
}
return result;
}
int main()
{
using namespace std;
auto s = "!the 54 quick brown foxes jump over the 21 dogs."s;
cout << "before: " << quoted(s) << endl;
auto s2 = remove_letters(s);
cout << "after: " << quoted(s2) << endl;
return 0;
}

most efficient way to parse a string using c++ features

this might be a stupid question (I hope not) but it caught my mind and I'm trying to figure it out. What is the most efficient way to parse a string using c++ features?
I appreciate everyone's comments as I, am I'm sure everyone else is too, to become a better programmer!
Here is how I would do it right now with my current knowledge:
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
void parseLine(string &line)
{
constexpr char DELIMITER_ONE = '|';
constexpr char DELIMITER_TWO = '[';
for (int i = 0; i < line.length(); i++)
{
if (line[i] == DELIMITER_ONE || line[i] == DELIMITER_TWO)
{
line.erase(i, 1);
}
}
cout << line << endl;
}
int main()
{
std::string testString = "H|el[l|o|";
parseLine(testString);
system("pause");
return 0;
}
line.erase(
std::remove_if(line.begin(), line.end(),
[](char c) { return c == DELIMITER_ONE || c == DELIMITER_TWO; }
),
line.end()
);
See also: erase-remove idiom
One more way is to use the boost regex library. Check the below code:
#include <iostream>
#include <string>
#include <boost/regex.hpp>
int main(){
std::string testString = "H|el[l|o|";
boost::regex rx("\\||\\[");
std::string replace = "";
std::string out = boost::regex_replace(testString, rx, replace);
std::cout << out << std::endl;
}
C++14 now includes regular expressions standard:
#include <iostream>
#include <string>
#include <regex>
std::string parseLine(const std::string& line);
int main() {
std::string testString = "H|el[l|o|";
std::string result = parseLine(testString);
std::cout << result << std::endl;
system("pause");
return 0;
}
std::string parseLine(const std::string& line) {
std::string input_string;
std::string result;
std::smatch sm;
std::regex r("([a-zA-Z]+)");
for(input_string = line; std::regex_search(input_string, sm, r); input_string = sm.suffix()) {
result.append(sm[0].str());
}
return result;
}

Make a backward string its own string?

I am brand new to programming so none of this may be right. I was just messing around trying to get the effect that I (finally) achieved. More for practice than anything else, but I wondered if there was another way to do it.
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1="Don't even think about it!";
string str2;
string str3;
string str4 = "";
for (int i = 0; i < str1.length(); i++){
str2 = str1.substr (0, str1.length()-i);
cout << str2 << str4;
for (int x = str2.length() - 1; x >= 0; x--){
str3 = str1[x];
cout << str3;
}
str4 = str4 + " ";
cout << "\n";
}
getch();
main();
return 0;
}
The question I have is this: Is there a way to make the str3, after it is backwards, its own string that I could then justify right instead of adding spaces with str4?
In order to get a reversed string, just pass the reverse-iterators to the constructor of a new string:
#include <iostream>
#include <string>
int main() {
std::string s = "this is a test";
std::string s_reversed(s.rbegin(), s.rend());
std::cout << s << "\n" << s_reversed << "\n";
}
The output is:
$ g++ test.cc && ./a.out
this is a test
tset a si siht
Applied to your problem:
#include <iostream>
#include <string>
int main() {
std::string s = "this is a test";
for (auto i = s.length(); i > 0; i--) {
std::cout << s;
std::cout << std::string(s.rbegin(), s.rend());
std::cout << '\n';
s[i-1] = ' ';
}
}
Note that there also is an algorithm in the standard library to reverse a container, e.g., a string: std::reverse().
For reference:
http://en.cppreference.com/w/cpp/string/basic_string/basic_string
http://en.cppreference.com/w/cpp/string/basic_string/rbegin
http://en.cppreference.com/w/cpp/string/basic_string/rend
http://en.cppreference.com/w/cpp/algorithm/reverse
You could try this:
replacing letters for whitespace and then reversing the string.
Concat the modified string with the reverse of it and print it.
std::string reverse(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
int main()
{
std::string str = "Don't even think about it!";
size_t N = str.length();
for (size_t i = 1; i < N; i++)
{
std::cout << str << reverse(str) << std::endl;
str.replace(N-i,1, " ");
}
return 0;
}
First I would rename the variables so it is more clear what you are trying to achieve. Believe me, in two months you will not have a clue what this code actually does. Suggestion:
str1 -> baseString
str2 -> forwardsClippedString
str3 -> backwardsClippedString
str4 -> gapString
Maybe these names are not even good but I think they are better than str1, ..., str4.
Then I would make a separate method of the inner loop. After that make a separate method of the outer for loop - yes, main() shouldn't be complicated at all.
Finally instead of recursively calling main I suggest to do a while-loop. An infinite one if you please (but it would be nice if one key quits the loop then).