Computer >> Máy Tính >  >> Lập trình >> C ++

Mã hóa một chuỗi trong C ++?


Cách đầu tiên là sử dụng một chuỗi chuỗi để đọc các từ được phân tách bằng dấu cách. Điều này có một chút hạn chế nhưng thực hiện nhiệm vụ khá tốt nếu bạn cung cấp các kiểm tra thích hợp.

ví dụ

#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   string str("Hello from the dark side");
   string tmp; // A string to store the word on each iteration.
   stringstream str_strm(str);

   vector<string> words; // Create vector to hold our words

   while (str_strm >> tmp) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
}

Ví dụ

Một cách khác là cung cấp dấu phân tách tùy chỉnh để chia chuỗi bằng cách sử dụng hàm getline -

#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   std::stringstream str_strm("Hello from the dark side");
   std::string tmp;
   vector<string> words;
   char delim = ' '; // Ddefine the delimiter to split by

   while (std::getline(str_strm, tmp, delim)) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
}