公共字符串计算

/**
 * 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.csdn.net/cogbee/article/details/8931838点击打开链接

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值