주석에서 언급 한 것처럼 문자열 (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;
}
결과 :
[C++에서 문자열을 분할하는 방법] 가능한 중복? (http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – CoryKramer
또한 http : // stackoverflow. com/questions/8448176/split-a-string-into-a-array-in-c – CoryKramer
@Cyber : 내 질문은 내 질문이 그들과 비슷하다고 생각하는 질문과 약간 다릅니다. –