关于#c++#的问题:输入字符串S,输出其包含的最长的英文字符子串

编写函数,输入字符串S,输出其包含的最长的英文字符子串。
例如abcd123fgh345”包含abcdfgh 两个英文字符串。


// 思路: 把字符串拆成单词的数组,再比较它们的长度,最后得到最长的。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
// 定义比较字符串长度的仿函数
class CompareStringLength
{
public:
bool operator ()(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? true : false;
}
};
int main()
{
vector<string> svec; // 定义字符串动态数组
string sWord; // 定义临时字符串对象
string TEXT;
cin>>TEXT;
// 循环跌带整个字符串
for(int i = 0; i < TEXT.size(); ++i)
{
if(isalpha(TEXT[i]) != 0)
{
// 如果第i个字符是字母, 就把它追加到临时字符串尾部
sWord.push_back(TEXT[i]);
}
else if(sWord.size() != 0)
{
// 如果第i个字符不是字母, 把临时字符串压入动态数组,并清空临时字符串
svec.push_back(sWord);
sWord.clear();
}
}
// 把最后一个临时字符串压入动态数组
if(sWord.size() != 0)
{
svec.push_back(sWord);
}
// 输出动态数组的值(可见拆分是否正确)
copy(svec.begin(), svec.end(), ostream_iterator<string>(cout, "\n"));
// 计算最大长度字符串,返回指向这个字符串的跌带器
vector<string>::iterator iter = max_element(svec.begin(),svec.end(), CompareStringLength());
// 输出这个字符串
cout << "最长字符串是: " << *iter << endl;
return 0;
}

运行结果如下:

img

代码:

#include <iostream>
#include <cstring>
using namespace std;
//输出最长字符串
void fun(char* s,char* sout)
{
    char tmp[100] = {0};
    int i=0,j=0;
    sout[0] = 0;
    while(1)
    {
        if(s[i] == '\0')
        {
            tmp[j] = '\0';
            if(strlen(tmp) > strlen(sout))
                strcpy(sout,tmp);
            break;
        }
        else if( (s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')  )
            tmp[j++] = s[i];
        else
        {
            tmp[j] = '\0';
            if(strlen(tmp) > strlen(sout))
                strcpy(sout,tmp);
            tmp[0] = '\0';
            j = 0;
        }
        i++;
    }
    
}

int main()
{
    char s[100],sout[100];
    cout <<"请输入一个字符串:";
    cin.getline(s,100); //输入一行
    //调用函数
    fun(s,sout);
    cout <<"最长的英文字符串:"<< sout<<endl;
    return 0;
}

你题目的解答代码如下:

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

int main()
{
    string str, s="", maxstr="";
    int i, j;
    getline(cin,str);
    for (i = 0; i <= str.size(); i++)
    {
        if(i < str.size() && (str[i]>='a' && str[i]<='z' || str[i]>='A' && str[i]<='Z'))
        {
            s.push_back(str[i]);
        }
        else
        {
            if (s.size() > maxstr.size())
                maxstr = s;
            s = "";
        }
    }
    cout << maxstr;
    return 0;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img