Advertisement
Taraxacum

tokenize_and_reorder

Nov 6th, 2020
1,830
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <cctype>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main(int argc, char const* argv[])
  7. {
  8.     char* buffer = new char[128];
  9.     char** words = new char*[16];
  10.  
  11.     // 读入一行字符串
  12.     cin.getline(buffer, 128);
  13.  
  14.     // 跳过开头的空白字符,找到第一个单词
  15.     char* head = buffer;
  16.     while (*head && isspace(*head)) {
  17.         head++;
  18.     }
  19.  
  20.     size_t word_idx = 0;
  21.     words[word_idx++] = head;
  22.  
  23.     while (*head) {
  24.         // 读第一个单词
  25.         while (*head && !isspace(*head)) {
  26.             head++;
  27.         }
  28.  
  29.         // 跳过空白字符
  30.         while (*head && isspace(*head)) {
  31.             *head = '\0';
  32.             head++;
  33.         }
  34.  
  35.         words[word_idx++] = head;
  36.     }
  37.  
  38.     // 输出单词数
  39.     cout << word_idx - 1 << endl;
  40.  
  41.     // 读取输出顺序
  42.     char* sequence = new char[word_idx];
  43.     cin.getline(sequence, word_idx);
  44.  
  45.     // 输出单词
  46.     for (size_t i = 0; i < word_idx - 1; i++) {
  47.         cout << words[sequence[i] - '0'] << ' ';
  48.     }
  49.  
  50.     cout << endl;
  51.  
  52.     delete[] buffer;
  53.     delete[] words;
  54.     delete[] sequence;
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement