uacs2024

导航

复试C++16真题_程序设计1_输出句子中每个单词长度

输入一行文本,按照相应格式输出每个单词的长度

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <iomanip>

int main(){
    string sen = "  qwe asd  axs  zfsfs ddwfa s";
    //getline(cin,sen);   如果要把输入的空格的记录进string里面,就要用getline(cin,sen);
    vector<string> letter;
    int size = sen.size();
    
    int left = -1;
    int i;
    for(i = 0;i < size;i++){
        if(sen[i]>='a'&&sen[i]<='z' || sen[i]>='A'&&sen[i]<='Z'){
            if(left == -1)  {left = i;}
        }
        else if(left != -1){
            letter.push_back( sen.substr(left,i-left) );
            left = -1;
        }
    }
    if(left != -1)  letter.push_back( sen.substr(left,i-left) );
    
    cout << setw(8) << "word" << setw(8) << "lenth" << endl;
    for(int i = 0;i < letter.size();i++){
        cout << setw(8) << letter[i] << setw(8) << letter[i].size() << endl;
    }
}

结果

 

posted on 2024-03-21 18:50  ᶜʸᵃⁿ  阅读(9)  评论(0编辑  收藏  举报