Hi all,
I have following string
0x0002,A5651QPR87GBZ094RTF52,D,A,000001,ABC ,10000.00 , EOT
i need to split the above using ',' as the delimiter & put those in to the following string variables.
1.Command
2.Key
3.Msgtype
4.number
5.name
6.amount
pls reply me as sap.
Regards

Dani AI

Generated

A couple of practical considerations for your input line: it contains spaces around several fields, and there are more than six comma-separated tokens (e.g., a trailing EOT). After splitting, be sure to trim whitespace, validate the field count, and decide whether to ignore extra tokens. Also, if you ever expect quoted fields with embedded commas, use a CSV parser instead of naive splitting; CSV rules are described in RFC 4180.

If you want a concise solution that trims each field, Boost.StringAlgo does the heavy lifting:

#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>

std::string command, key, msgtype, number, name, amount;

std::string line = /* your input */;
std::vector<std::string> fields;
boost::split(fields, line, boost::is_any_of(","));
for (auto& f : fields) boost::trim(f);

if (fields.size() >= 6) {
  command = fields[0];
  key     = fields[1];
  msgtype = fields[2];
  number  = fields[3];
  name    = fields[4];
  amount  = fields[5]; // ignore EOT or other trailing tokens
} else {
  // handle malformed input
}

If you are on C++20, std::ranges::views::split lets you split without copying and then trim each subrange; see cppreference. For numeric conversion of number or amount, prefer std::from_chars when available to avoid locale surprises and exceptions (docs). Finally, avoid strtok: it modifies the buffer and is not thread-safe; stick with C++ string utilities or a CSV library.

Recommended Answers

All 9 Replies

You can use string.find and string.substr for that
Here's a with an example

int main()
{
    string str = "0x0002,A5651QPR87GBZ094RTF52,D,A,000001,ABC ,10000.00 , EOT";
    string word;
    stringstream stream(str);
    while( getline(stream, word, ',') )
        cout << word << "\n";
}

Nothing magical going on here, but in an uncharacteristic move, I actually added comments. Yes, I'm bored:

#include <string>
#include <vector>

//! Maintains a collection of substrings that are
//! delimited by a string of one or more characters
class Splitter {
  //! Contains the split tokens
  std::vector<std::string> _tokens;
public:
  //! Subscript type for use with operator[]
  typedef std::vector<std::string>::size_type size_type;
public:
  //! Create and initialize a new Splitter
  //!
  //! \param[in] src The string to split
  //! \param[in] delim The delimiter to split the string around
  Splitter ( const std::string& src, const std::string& delim )
  {
    reset ( src, delim );
  }

  //! Retrieve a split token at the specified index
  //!
  //! \param[in] i The index to search for a token
  //! \return The token at the specified index
  //! \throw std::out_of_range If the index is invalid
  std::string& operator[] ( size_type i )
  {
    return _tokens.at ( i );
  }

  //! Retrieve the number of split tokens
  //!
  //! \return The number of split tokesn
  size_type size() const
  {
    return _tokens.size();
  }

  //! Re-initialize with a new soruce and delimiter
  //!
  //! \param[in] src The string to split
  //! \param[in] delim The delimiter to split the string around
  void reset ( const std::string& src, const std::string& delim )
  {
    std::vector<std::string> tokens;
    std::string::size_type start = 0;
    std::string::size_type end;

    for ( ; ; ) {
      end = src.find ( delim, start );
      tokens.push_back ( src.substr ( start, end - start ) );

      // We just copied the last token
      if ( end == std::string::npos )
        break;

      // Exclude the delimiter in the next search
      start = end + delim.size();
    }

    _tokens.swap ( tokens );
  }
};

#include <iostream>

int main()
{
  const std::string line =
    "0x0002,A5651QPR87GBZ094RTF52,D,A,000001,ABC ,10000.00 , EOT";

  Splitter split ( line, "," );

  for ( Splitter::size_type i = 0; i < split.size(); i++ )
    std::cout<<'|'<< split[i] <<"|\n";
}

OMG Narue, why did you make that soooo difficult ?? I think you outdid yourself on this one:) See my post if you missed it.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
	char str[] = "0x0002,A5651QPR87GBZ094RTF52,D,A,000001,ABC ,10000.00 , EOT";
	char* pch;
	pch = strtok(str, ", ");
	while (pch != NULL) {
		cout << pch << endl;
		pch = strtok(NULL, ", ");
	}
	return 0;
}

>OMG Narue, why did you make that soooo difficult ??
>See my post if you missed it.
I didn't make it difficult, and I did see your post. Do please modify your code to accept "::" as a delimiter to see where I was going with my class. ;)

Hi all thanks a lot. i managed to modify it as follows.it worked.
int main()
{
string str = "0x0002,A5651QPR87GBZ094RTF52,D,A,000001,ABC ,10000.00 , EOT";

stringstream stream;
stream<<str
}

This is another one of those "common" questions that I am recommending cataloging:

Please vote for it!

Dave

commented: No -2

I am having some warning when im using strtok.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.