输入过程中getline会认为是一个字符串,所以利用string中的find()函数找到第一次出现空格,并用assign()进行复制计算,分成两个string。
string s,s1,s2;
getline(cin,s);
int len=s.length();
int k=s.find_first_of(' ',0);
s1.assign(s,0,k);
s2.assign(s,k+1,len);//分成两个s1,s2
计算两个字符串的最大公共子串(Longest Common Substring)的长度,字符不区分大小写。
第一种方法,直接进行比较和循环嵌套,由于是不区分大小写,大小写之间的差值是32.
#include <iostream>
#include <string>
using namespace std;
int getCommonStrLength( char *pFirstStr, char *pSecondStr)
{
int i,max;
char *binF,*endF,*binS,*endS;
max=0;
for (binF=pFirstStr;*binF!='\0';binF++)
{
endF=binF;
for (binS=pSecondStr;*binS!='\0';binS++)
{
endS=binS;
i=0;
while(*endF!='\0' && *endF!='\0'&& (*endF==*endS ||*endF==(*endS+'A'-'a') ||*endS==(*endF+'A'-'a')))
{
i++;
endF++;
endS++;
}
if(max<=i)
max=i;
}
}
return max;
}
int main()
{
char s1[100],s2[100];
cin>>s1;
cin>>s2;
int result=getCommonStrLength( s1, s2);
cout<<result<<endl;
system("pause");
return 0;
}
是数字最大的就是公共字符串的个数。用的是vector矢量。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int getCommonStrLength(string pFirstStr, string pSecondStr)
{
if( (pFirstStr==" ")|| (pSecondStr==" "))
return 0;
int m=pFirstStr.size();
int n=pSecondStr.size();
vector<vector<int> > table(m+1,vector<int>(n+1));
int max=0;
for(int i=0;i<m+1;++i)
{
for(int j=0;j<n+1;++j)
{
if(i==0||j==0)
table[i][j]=0;
else if(pFirstStr[i-1]==pSecondStr[j-1])
{
table[i][j]=table[i-1][j-1]+1;
if(table[i][j]>max)
max=table[i][j];
}
else
table[i][j]=0;
}
}
return max;
}
int main()
{
string s,s1,s2;
getline(cin,s);
int len=s.length();
int k=s.find_first_of(' ',0);
s1.assign(s,0,k);
s2.assign(s,k+1,len);
int result=getCommonStrLength( s1, s2);
cout<<result<<endl;
system("pause");
return 0;
}