2014-10-17 2 views
0

문장이 있습니다. 문장을 분할하여 각 단어를 배열 항목에 추가합니다.
다음 코드를 완료했지만 여전히 잘못되었습니다.문장을 분할하여 배열 항목의 각 단어를 추가합니다.

string str = "Welcome to the computer world."; 
string strWords[5]; 
short counter = 0; 
for(short i=0;i<str.length();i++){ 
    strWords[counter] = str[i]; 
    if(str[i] == ' '){ 
     counter++; 
    } 
} 
+1

[C++에서 문자열을 분할하는 방법] 가능한 중복? (http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – CoryKramer

+0

또한 http : // stackoverflow. com/questions/8448176/split-a-string-into-a-array-in-c – CoryKramer

+0

@Cyber ​​: 내 질문은 내 질문이 그들과 비슷하다고 생각하는 질문과 약간 다릅니다. –

답변

2

당신이 당신의 실수로부터 배워야하기 때문에 나는 대답 해요 : : 그냥 += 문자열 연산자를 사용하여 코드가 작동합니다

// strWords[counter] = str[i]; <- change this 
strWords[counter] += str[i];  <- to this 

는 공백을 제거하지만, 여기에 당신의 "수정"버전입니다 (당신이 그들을 추가하지 않으려면) 단지, 같은 공간 검사의 순서를 변경 : 내가 중복 링크를 사용하여 제안하고있어 어쨌든

for (short i = 0; i<str.length(); i++){ 
    if (str[i] == ' ') 
     counter++; 
    else 
     strWords[counter] += str[i]; 
} 

Split a string in C++? too

+1

감사합니다. 대답은 가장 간단합니다. –

+1

@LionKing 당신은 현재 단어에 문자를 추가 한 후에 만 ​​공간을 확인하기 때문에 문장에 공백이 여전히 각 단어에 추가된다는 것을 알고 계십니까? –

+0

@RudolfsBundulis : 팁 주셔서 감사합니다. 그러나 나는 각 단어마다 어떤 공간도 보지 못한다. –

1

매우 못 생기는 방법으로, @Cyber는 최상의 대답에 연결되어 있습니다.

string str = "Welcome to the computer world."; 
string strWords[5]; 
short counter = 0; 

for(short i=0;i<str.length();i++){ 
    if(str[i] == ' '){ 
     counter++; 
     i++; 
    } 
    strWords[counter] += str[i]; 
} 
0

주석에서 언급 한 것처럼 문자열 (strtok, std 기능 등)을 분할하는 더 편리한 방법이 많이 있지만 예제에 관해서는 'str [ I] '하지만이 같은 현재 단어에 추가 할 단일 문자이기 때문에, 그것을 추가 :

string str = "Welcome to the computer world."; 
string strWords[5]; 
short counter = 0; 
for(short i=0;i<str.length();i++){ 
    if(str[i] == ' ' && !strWords[counter].empty()){ 
     counter++; 
    } 
    else { 
     strWords[counter] += str[i]; 
    } 
} 

는하지만 배열에 액세스 할 수 있기 때문에이 만 주어진 입력 데이터에서 작동합니다 strWords 너는 5 개 단어가있는 경우에 외부 경계. 난 당신이 C++에 새로운 가정 때문에

은 여기 (만 추가 연산자를 사용하는 경우) 당신이 가지고있는 공간 문제의 데모입니다

string str = "Welcome to the computer world."; 
vector<string> strWords; 
string currentWord; 
for(short i=0;i<str.length();i++){ 
    if(str[i] == ' ' && !currentWord.empty()){ 
     strWords.push_back(currentWord); 
     currentWord.clear(); 
    } 
    else { 
     currentWord += str[i]; 
    } 
} 

UPDATE : 후속 코드를 사용하는 것을 고려

#include <string> 
#include <iostream> 

using namespace std; 

int main(int argc, char** argv) 
{ 
    string str = "Welcome to the computer world."; 
    string strWords[5]; 
    short counter = 0; 
    for(short i=0;i<str.length();i++){ 
     strWords[counter] += str[i]; // Append fixed 
     if(str[i] == ' '){ 
      counter++; 
     } 
    } 
    for(short i=0;i<5;i++){ 
     cout << strWords[i] << "(" << strWords[i].size() << ")" << endl; 
    } 
    return 0; 
} 

결과 :

Space at the end of each string

+0

귀하의 답변과 설명에 대해 감사드립니다. –

관련 문제