-7

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;
}
  • check this thread :) http://stackoverflow.com/questions/5891610/how-to-remove-characters-from-a-string – Kenion Sep 04 '15 at 04:16
  • 1
    Is `std::cout` really that scary? It's just another name for exactly the same thing. – john Sep 04 '15 at 04:17
  • 1
    Your question is ambiguous, do you want to remove all spaces from a string, do you just want to remove them from the end of a string, maybe you want to remove them from then beginning and end but not the middle? You need to ask a clear question if you want an appropriate answer. – john Sep 04 '15 at 04:19

3 Answers3

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

shanmuga
  • 4,329
  • 2
  • 21
  • 35
0

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

Gilad Pellaeon
  • 111
  • 1
  • 1
  • 11
0

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;
}
Community
  • 1
  • 1
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50