2017-09-08 10 views
-1

文字列を2次元配列token[100][100]に分割するプログラムを作成しようとしていました。それは文字列全体を別々の単語に分割しますが、単語をピリオドに渡すたびにtoken[i++][j]する必要があります。これまで私はこれを持っています。文字から文字列を分割する

#include <iostream> 
#include <istream> 
#include <string> 
#include <sstream> 
#include <vector> 
#include <algorithm> 
using namespace std; 
int main() 
{ 
    string code; 
    getline(cin, code); 
    string codef[100]; 
    string token[100][100]; 
    int j = 0, i=0; 
    for (i = 0; i < 2; i++) { 
     stringstream ssin(code); 
     while (ssin.good() && j < 4) { 
      ssin >> token[i][j]; 
      ++j; 
      if (token[i][j] == ".") { 
       break; 
      } 
     } 
    } 

    for (i = 0; i < 4; i++) { 
     for (j = 0; j < 4; j++) { 
      cout << token[i][j] << endl; 
     } 
     cout << endl; 
    } 
    return 0; 
} 

それは別の文字列をチェックし、ので、私はそれが時間の前にスペースを入れてする必要があります行っている方法で、あなたの束のような場合はその期間:「こんにちは。」それは明らかにそれを認識しません。私はそれが起こることを望んでいない、この作品を作る良い方法はありますか?今は文章を2文と4文(文章あたり4語)に制限しています。

答えて

1

単純なバニラstd :: stringで区切り文字を検索するのに、単にstd::string::find_first_ofを使用しないのはなぜですか?何も見つからない場合はstd::string::nposを返します。 Btw:私は本当にstd :: arrayまたはstd :: vectorの良い古い配列のものを削除することを提案します。 std :: vectorを使うと、ハードコードされた制限を取り除くことができます。

とにかく、ここに私が示唆しているものがあります。注:ベクタに移行してpush_backを使用するか、またはに制限チェックを追加するかのいずれかで、コードを読みやすくするために配列アクセスの制限チェックを省略しました。

私はこのコードはほとんど説明できないと思いますが、if(pos > last_pos)が必要です。pos == last_posは別の区切り文字が見つからないためです。

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string code = "The quick brown fox jumps over the lazy dog. Lorem ipsum dolor. Cooky"; 

    std::string token[100][100]; 
    std::size_t last_pos = 0, pos; 
    int sentence = 0, word = 0; 
    while ((pos = code.find_first_of(". ", last_pos)) != std::string::npos) 
    { 
     if (pos > last_pos) 
      token[sentence][word] = code.substr(last_pos, pos-last_pos /*length*/); 

     if(code.substr(pos, 1)[0] == '.') 
     { 
      ++sentence; 
      word = 0; 
     } 
     else 
      ++word; 
     last_pos = pos+1; 
    } 
    if (last_pos < code.length()) 
     token[sentence][word] = code.substr(last_pos, std::string::npos); 


    for (int i = 0; i < 4; i++) { 
     for (int j = 0; j < 4; j++) { 
      std::cout << token[i][j] << std::endl; 
     } 
     std::cout << std::endl; 
    } 

    return 0; 
} 

出力があるため、あなたのハードコードされた制限のため、不明瞭に少しですが、それがあるように私はそれを残しているが、文字列の分割とは何の関係もありません:

The 
quick 
brown 
fox 


Lorem 
ipsum 
dolor 


Cooky 
関連する問題