How do I truncate a string in C++?

Asked 1 years ago, Updated 1 years ago, 140 views

In Java, we could've used the bottom together Is there an easy way to do it in C++?

String str = "The quick brown fox";
String[] results = str.split(" ");

string c++ tokenize

2022-09-21 17:26

1 Answers

/*c++11 or higher*/
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;


int main(int, char**)
{
    string text = The quick brown fox"; //string to token

    char_separator<char> sep(", "); //token delim
    tokenizer<char_separator<char>> tokens(text, sep);
    for (const auto& t : tokens) {
        cout << t << "." << endl;
    }
}

/*c++less than 11*/
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
    string text = "token, test string"; //token string

    char_separator<char> sep(", "); //token delim
    tokenizer< char_separator<char> > tokens(text, sep);
    BOOST_FOREACH (const string& t, tokens) {
        cout << t << "." << endl;
    }
}
 std::string str = "The quick brown fox"; //token string

  // Create a stringstream from string
  std::stringstream strstr(str);

  // Use an interpreter to copy except for spaces in the vector
  std::istream_iterator<std::string> it(strstr);
  std::istream_iterator<std::string> end;
  std::vector<std::string> results(it, end);

  // Output
  std::ostream_iterator<std::string> oit(std::cout);
  std::copy(results.begin(), results.end(), oit);

You can use it with that.


2022-09-21 17:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.