/**
* Copyright (C) 2014, CSU
* All rights reserved
* File Name:test.cpp
* Author: lmm
* Date of completion: 2015/1/12
* Version: v1.0
*
* 问题描述:公共字符串计算(计算两个字符串的最大公共字符串的长度,字符不区分大小写)
* 输入描述: 输入两个字符串
* 详细描述:原型: int getCommonStrLength(char *pFirstStr, char *pSecondStr)
* 输入参数:char *pFirstStr. // 第一个字符串 char *pSecondStr //第二个字符串
* 知识点 : 字符串,查找
* 程序输出: 输出整数一个整数
*/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
int getCommonStrLength(char *pFirstStr, char *pSecondStr)
{
int length = 0;
while ((*pFirstStr == *pSecondStr)&&(*pFirstStr != '\0') && (*pSecondStr != '\0'))
{
++pFirstStr;
++pSecondStr;
length++;
}
return length;
}
int main()
{
string str,sstr,strTemp;
cin >> str;
cin >> sstr;
int length_common = 0 ;
int length_max = 0;
<em><span style="color:#cc0000;">for(string::size_type index = 0; index != str.size(); ++index)
{
str[index] = tolower(str[index]);
}
for(string::size_type index = 0; index != sstr.size(); ++index)
{
sstr[index] = tolower(sstr[index]);
}</span></em>
if (sstr.length() > str.length())
{
strTemp = str;
str = sstr;
sstr = " ";
sstr = strTemp;
}
<em><span style="color:#cc0000;">char *s_First = (char*)malloc((str.length()+1)*sizeof(char));
str.copy(s_First,str.length(),0);
s_First[str.length()] = '\0';
char *s_Second = (char*)malloc((sstr.length()+1)*sizeof(char));
sstr.copy(s_Second,sstr.length(),0);
s_Second[sstr.length()] = '\0';</span></em>
char *Temp;
Temp = s_Second;
int i = 0 , j = 0;
while(*s_First != '\0' )
{
while (*s_Second != '\0')
{
if(*s_First == *s_Second)
{
length_common = getCommonStrLength(s_First,s_Second);
if (length_common > length_max)
{
length_max = length_common;
}
}
s_Second++;
}
s_First++;
s_Second = Temp;
}
cout << length_max << endl;
return 0;
}
总结:
遇到问题,首先要仔细分析问题,问题的逻辑性有时候比写代码更重要,逻辑分析不对,写的代码自然运行错误。将问题的整体逻辑写下来。
问题:
(一)斜体部分1
针对string类型,不能简单的用int类型。任何存储string的size操作结果的变量必须为string::size_type类型。特别重要的是,不能把size的返回值赋给一个int变量
(二)斜体部分2
string类型与char*类型的转换
http://blog.youkuaiyun.com/cogbee/article/details/8931838点击打开链接