2016-09-14 4 views
1

Я пишу метод в C++, который будет принимать строку из 2 или более слов и выводит каждое отдельное слово строки, разделенной секундой или так, используя метод sleep(). Я пытаюсь сделать это, используя цикл for и подстроки. Я также не уверен в регулярных выражениях, которые следует использовать и как их использовать, для достижения желаемого результата.Принимая каждое отдельное слово из строки в C++

Я рассмотрел this и this и найду свой вопрос, поскольку я пытаюсь сделать это в цикле и не хранить отдельные подстроки.

Входной сигнал:

"Это пример"

Желаемый выход:

"Эта" (пауза) "является" (пауза) "AN" (пауза) " пример."

ответ

8

Использование std::stringstream, не требуется никаких регулярных выражений:

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

int main() { 
    stringstream ss("This is a test"); 
    string s; 

    while (ss >> s) { 
     cout << s << endl; 
    } 

    return 0; 
} 

Также см How do I tokenize a string in C++?

+0

Элегантное решение. – caps

+0

На данный момент моя реализация выглядит следующим образом: 'void speak (string statement) { string temp; stringstream ss (statement); while (ss >> temp) { sleep (1); cout << temp << ""; } 'Как я могу сделать эту паузу, прежде чем произносить каждое отдельное слово? –

+0

Я сожалею, что выглядит так уродливо ... –

1

вы можете реализовать свой собственный метод:

//StrParse.h 

    #pragma once 

    #include <iostream> 

    static counter = 0; 

    char* strPar(char* pTxt, char c) 
    { 

     int lenAll = strlen(pTxt); 

     bool strBeg = false; 
     int nWords = 0; 


     for(int i(0); i < lenAll; i++) 
     { 
      while(pTxt[i] != c) 
      { 
       strBeg = true; 
       i++; 
      } 
      if(strBeg) 
      { 
       nWords++; 
       strBeg = false; 
      } 

     } 

     int* pLens = new int[nWords]; 
     int j = 0; 
     int len = 0; 

     for(i = 0; i < lenAll; i++) 
     { 
      while(pTxt[i] != c) 
      { 
       strBeg = true; 
       i++; 
       len++; 
      } 
      if(strBeg) 
      { 
       pLens[j] = len; 
       j++; 
       strBeg = false; 
       len = 0; 
      } 

     } 

     char** pStr = new char*[nWords + 1]; 

     for(i = 0; i < nWords; i++) 
      pStr[i] = new char[pLens[i] + 1]; 

     int k = 0, l = 0; 

     for(i = 0; i < lenAll; i++) 
     { 
      while(pTxt[i] != c) 
      { 
       strBeg = true; 
       pStr[k][l] = pTxt[i]; 
       l++; 
       i++; 
      } 
      if(strBeg) 
      { 
       pStr[k][l] = '\0'; 
       k++; 
       l = 0; 
       strBeg = false;  
      } 

     } 

     counter++; 

     if(counter <= nWords) 
      return pStr[counter - 1]; 
     else 
      return NULL; 
    } 


    //main.cpp 


    #include "StrParse.h" 

    void main() 
    { 

     char* pTxt = " -CPlusPlus -programming -is -a - superb thing "; 
     char* pStr1 = NULL; 
     int i = 1; 
     char sep; 

     std::cout << "Separator: "; 
     sep = std::cin.get(); 
     std::cin.sync(); 

     while(pStr1 = strPar(pTxt, sep)) 
     { 
      std::cout << "String " << i << ": " << pStr1 << std::endl; 
      delete pStr1; 
      i++; 
     } 

     std::cout << std::endl; 
    } 
2

Вот пара реализаций, которые дон» t включать создание посторонних буферов.

#include <boost/range/adaptor/filtered.hpp> 
#include <boost/range/algorithm/copy.hpp> //for boost::copy 

#include <chrono> 
#include <iostream> 
#include <string> 
#include <experimental/string_view> //in clang or gcc; or use boost::string_ref in boost 1.53 or later; or use boost::iterator_range<char*> in earlier version of boost 
#include <thread> 

void method_one(std::experimental::string_view sv) 
{ 
    for(auto b = sv.begin(), e = sv.end(), space = std::find(b, e, ' ') 
     ; b < e 
     ; b = space + 1, space = std::find(space + 1, e, ' ')) 
    { 
     std::copy(b, space, std::ostreambuf_iterator<char>(std::cout)); 
     std::cout << " (pause) "; //note that this will spit out an extra pause the last time through 
     std::this_thread::sleep_for(std::chrono::seconds(1)); 
    } 
} 

void method_two(std::experimental::string_view sv) 
{ 
    boost::copy(
     sv | boost::adaptors::filtered([](const char c) -> bool 
     { 
      if(c == ' ') 
      { 
       std::cout << " (pause) "; //note that this spits out exactly one pause per space character 
       std::this_thread::sleep_for(std::chrono::seconds(1)); 
       return false; 
      } 

      return true; 
     }) 
     , std::ostreambuf_iterator<char>(std::cout) 
    ); 
} 

int main() { 
    const std::string s{"This is a string"}; 

    method_one(s); 
    std::cout << std::endl; 
    method_two(s); 
    std::cout << std::endl; 

    return 0; 
} 

Live on coliru, если вы в этом.

Смежные вопросы