LCS算法示例的主函数调用

本文详细介绍了C++中将字符串转换为宽字符串,再将宽字符串转换回普通字符串的方法,并通过实现最长公共子序列算法来比较两个字符串的相似度。

作者finallyly 出处 博客园(转载请注明作者和出处)

ExpandedBlockStart.gifmain.cpp
#include "stdafx.h"
#include 
"stringprocess.h"
#include 
<iostream>
#include 
"windows.h"
using namespace std;
wstring String2Wstring(
string sResult)
{
    
int iWLen=MultiByteToWideChar( CP_ACP, 0, sResult.c_str(), sResult.size(), 00 );// 计算转换后宽字符串的长度。(不包含字符串结束符)  

    wchar_t 
*lpwsz= new wchar_t [iWLen+1];  


    MultiByteToWideChar( CP_ACP, 
0, sResult.c_str(), sResult.size(), lpwsz, iWLen ); // 正式转换。  

    lpwsz[iWLen] 
= L'\0';   

    wstring wsResult(lpwsz);  

    delete []lpwsz;  

    
return wsResult;  
    
}

string Wstring2String(wstring wsResult)
{
    
string sResult;  
    
int iLen= WideCharToMultiByte( CP_ACP, NULL, wsResult.c_str(), -1, NULL, 0, NULL, FALSE ); // 计算转换后字符串的长度。(包含字符串结束符)  
    char *lpsz= new char[iLen];  
    WideCharToMultiByte( CP_OEMCP, NULL, wsResult.c_str(), 
-1, lpsz, iLen, NULL, FALSE); // 正式转换。  
    sResult.assign( lpsz, iLen-1 ); // 对string对象进行赋值。  
    delete []lpsz;  
    
return sResult;

}

int _tmain(int argc, _TCHAR* argv[])
{
    

    

    
    wstring wstr1
=L"生命无国界,我们不应该庆祝日本地震";
    wstring wstr2
=L"我们的生命无国界,因此不应该庆祝日本地震";
    
string str1=Wstring2String(wstr1);
    
string str2=Wstring2String(wstr2);
    cout
<<"待对比的字符串为:"<<endl;
    cout
<<"x串: "<<str1.c_str()<<endl;
    cout
<<"y串: "<<str2.c_str()<<endl;
    
const wchar_t *xpart=wstr1.c_str();
    
const wchar_t *ypart=wstr2.c_str();
    stringprocess p;
    
int len=p.CalculateLongestCommonSequenceLen(xpart,ypart);
    
if (len>0)
    {
        wstring wlcsequence
=p.GetLongestCommonSequence();
        
string lcsequence=Wstring2String(wlcsequence);
        cout
<<"最大公共字串为:"<<lcsequence.c_str()<<endl;
        
int*xpartinfo=new int[wlcsequence.size()];
        
int *ypartinfo=new int[wlcsequence.size()];
        p.GetIndexesInfo(xpartinfo,ypartinfo);
        cout
<<"最大公共字串在x字符串中的位置:"<<endl;
        
for (int i=0;i<wlcsequence.size();i++)
        {
            cout
<<xpartinfo[i]<<";";
        }
        cout
<<endl;
        cout
<<"最大公共字串在y字符串中的位置:"<<endl;
        
for (int i=0;i<wlcsequence.size();i++)
        {
            cout
<<ypartinfo[i]<<";";
        }cout
<<endl;

        delete xpartinfo;
        delete ypartinfo;

    }
    cout
<<len<<endl;

    
    cout
<<"finish"<<endl;
    
int f;
    cin
>>f;
    
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值