cstring转string,int,float,double,dword;全半角转换;切分替换函数;日期、序号产生函数


自己写了一个命名空间,gcs。包含了
1.cstring转string,int,float,double,dword;
2.全半角转换;
3.切分替换函数;
4.日期、序号产生函数。

部分代码vs2010编译运行通过。

/******************************************************************************
*
* Copyright (c) 2014,SaiOlive
* Filename:  iSpace.h
* Author:    SaiOlive
* Version:   1.0
* Editdate:  2014.11.11
* Func List: 1.Convert:CString to others;SBC to DBC;
*              others include string,int,float,double,DWORD(IP address ctrl)
*            2.Split,Replace;
*            3.Generate Date,Serial Number;
*
* History:   2014.11.11     SaiOlive            Edit comments
*
* Others:
*
******************************************************************************/

#pragma once

#ifndef _ISPACE_H_
#define _ISPACE_H_

#include 
   
   
    
    
#include 
    
    
     
     

#include "stdafx.h"

#define _GCS_BEG        namespace gcs {
#define _GCS_END        }

_GCS_BEG


///
//                                                                           //
//                             1. Convert                                    //
//                                                                           //
///
  
/******************************************************************************
*
* Function:       CString To string
* Description:    
* Input:          csInput         Input CString
* Output:         
* Return:         Exec Success    Output string
*                 Exec Failure    L""
*
* Others:         2011.10.22      SaiOlive            Original 
*                 2012.11.16      SaiOlive            Optimal
*
******************************************************************************/
inline std::string CStr2Str(const CString& csInput);

/******************************************************************************
*
* Function:       CString To int
* Description:
* Input:          csInput         Input CString
* Output:
* Return:         int
*
* Others:         2014.09.09      SaiOlive            Original
*
******************************************************************************/
inline int CStr2Int(const CString& csStr);
 
/******************************************************************************
*
* Function:       CString To float
* Description:
* Input:          csInput         Input CString
* Output:
* Return:         float
*
* Others:         2014.09.09      SaiOlive            Original
*
******************************************************************************/
inline float CStr2Fl(const CString& csStr);

/******************************************************************************
*
* Function:       CString To double
* Description:
* Input:          csInput         Input CString
* Output:
* Return:         double
*
* Others:         2014.09.09      SaiOlive            Original
*
******************************************************************************/
inline double CStr2Db(const CString& csStr);

/******************************************************************************
*
* Function:       CString To DWORD
* Description:
* Input:          csIp            Input CString
* Output:
* Return:         DWORD
*
* Others:         2014.09.09      SaiOlive            Original
*
******************************************************************************/
inline DWORD IpTransform(CString csIp);

/******************************************************************************
*
* Function:       DWORD To CString
* Description:
* Input:          dwIp            Input dwIp
* Output:
* Return:         CString
*
* Others:         2014.09.09      SaiOlive            Original
*
******************************************************************************/
inline CString IpTransform(const DWORD& dwIp);

/******************************************************************************
*
* Function:       SDC To DBC
* Description:    SBC case To DBC case                eg.:"A" To "A"
*
* Input:          strSbc          SDC string
* Output:
* Return:         Exec Success    DBC string
*                 Exec Failure    ""
*
* Others:         2012.11.16      SaiOlive            Original
*
******************************************************************************/
inline std::string Sbc2Dbc(const std::string& strSbc);


///
//                                                                           //
//                           2. Split,Replace                                //
//                                                                           //
///

/******************************************************************************
*
* Function:       Split CString with Flag
* Description:    Input:"A;B;C"    Flag:";"           Result:"A" "B" "C"
*                 Input:"A;B;;"    Flag:";"           Result:"A" "B" "" ""
*
* Input:          csStr        
*                 csFlag
*
* Output:         vecElement
*
* Return:         Exec Success    Element Number
*                 Exec Failure    0
*
* Note:           At the beginning,it didn't clear the vector.            
*
* Others:         2012.12.18      SaiOlive            Original
*                 2013.09.29      SaiOlive            Edited comments
*
******************************************************************************/
inline int SplitCStr(const CString& csStr, const CString& csFlag, std::vector
     
     
      
      & vecElement);

/******************************************************************************
*
* Function:       Split string with Flag
* Description:    Input:"A;B;C"    Flag:";"           Result:"A" "B" "C"
*                 Input:"A;B;;"    Flag:";"           Result:"A" "B" "" ""
*
* Input:          strStr
*                 strFlag
*
* Output:         vecElement
*
* Return:         Exec Success    Element Number
*                 Exec Failure    0
*
* Note:           At the beginning,it didn't clear the vector.
*
* Others:         2012.12.18      SaiOlive            Original
*
******************************************************************************/
inline int SplitString(const std::string& strStr, const std::string& strFlag, std::vector
      
      
       
        &vecElement);

/******************************************************************************
*
* Function:       Split Names with Flag";"
* Description:    Input:"A;B;C"   Result:"A" "B" "C"
*                 Input:"A;B;B;;" Result:"A" "B"
*
* Input:          csStr
*
* Output:         vecElement
*
* Return:         Exec Success    Element Number
*                 Exec Failure    0
*
* Note:           At the beginning,it clear the vector.
*
* Others:         2012.12.18      SaiOlive            Original
*                 2013.09.29      SaiOlive            Removal same names
*                                                     Removal ";" end of CString
*
******************************************************************************/
inline int SplitNames(CString csStr, std::vector
       
       
         & vecElement); /****************************************************************************** * * Function: Replace String * Description: Replace the old string which is the part of string with new string. * * Input: strStr * strOld * strNew * * Output: strStr * * Return: Exec Success Replace Times * Exec Failure 0 * * Others: 2012.12.18 SaiOlive Original * ******************************************************************************/ inline int ReplaceString(std::string& strStr, const std::string& strOld, const std::string& strNew); /****************************************************************************** * * Function: Split Names with Flag";" * Description: Replace the old string which is the part of string with new string. * Input:"AAABB" Replace"AB"with"" Result:"A" * * Input: strStr * strOld * strNew * * Output: strStr * * Return: Exec Success Replace Times * Exec Failure 0 * * Others: 2012.12.18 SaiOlive Original * ******************************************************************************/ inline int ReplaceStringAll(std::string& strStr, const std::string& strOld, const std::string& strNew); /// // // // 3. Generate Date , Serial Number // // // /// /****************************************************************************** * * Function: Get Date CString * Description: * * Input: nStyle 0 Format:"2014.11.11" * 1(Default) Format:"2014-11-11"(Kbase date format) * Output: * * Return: Exec Success Date CString * Exec Failure L"" * * Others: 2011.09.01 SaiOlive Original * 2011.10.22 SaiOlive Changed return style from "string" to "bool" * 2012.11.16 SaiOlive Changed return style from "bool" to "string" * 2012.12.27 SaiOlive Changed return style from "string" to "cstring" * 2013.10.09 SaiOlive Changed nStyle defalut value from "0" to "1" * ******************************************************************************/ inline CString GetDate(int nStyle = 1 ); /****************************************************************************** * * Function: Get Time CString * Description: * * Input: nStyle 0 Format:"09:09:09" * 1(Default) Format:"09-09-09"(Kbase time format) * Output: * * Return: Exec Success Date CString * Exec Failure L"" * * Others: 2012.11.16 SaiOlive Original * 2013.10.09 SaiOlive Changed nStyle defalut value from "0" to "1" * ******************************************************************************/ inline CString GetTime(int nStyle = 1 ); /****************************************************************************** * * Function: Get Date and Time CString * Description: * * Input: nStyle 0 Format:"09:09:09" * 1(Default) Format:"09-09-09"(Kbase time format) * Output: * * Return: Exec Success Date CString * Exec Failure L"" * * Others: 2012.11.16 SaiOlive Original * 2013.10.09 SaiOlive Changed nStyle defalut value from "0" to "1" * ******************************************************************************/ inline CString GetDateAndTime(int nStyle = 1 ); /****************************************************************************** * * Function: Get Serial Number * Description: Get an int type of serial number.The length is 17. * eg. 20130201104253123 * * Input: * Output: ullSerialNum Serial Number * * Return: Exec Success true * Exec Failure flase * * Others: 2012.11.16 SaiOlive Original * 2013.02.01 SaiOlive Add comments * ******************************************************************************/ inline bool GetSerNumByTime(__int64 &ullSerialNum); /****************************************************************************** * * Function: Get Serial Number * Description: Get an CString type of serial number.The length is 17. * eg. 20130201104253123 * * Input: * Output: * Return: Exec Success Serial Number * Exec Failure L"" * * Others: 2012.11.16 SaiOlive Original * 2013.02.01 SaiOlive Add comments * ******************************************************************************/ inline CString GetSerNumByTime(); /****************************************************************************** *************************Function Implementations****************************** ******************************************************************************/ /// // // // 1. Convert // // // /// std::string CStr2Str(const CString& csInput) { try { std::wstring strIutput( csInput.GetString() ); int nLen = WideCharToMultiByte( CP_ACP , 0 , strIutput.c_str() , -1 , NULL , 0 , NULL , NULL ); if ( nLen <= 0 ) return NULL; char *_pcText = new char[nLen]; memset( _pcText , 0 , nLen ); WideCharToMultiByte( CP_ACP , 0 , strIutput.c_str() , -1 , _pcText , nLen , NULL , NULL ); std::string strOutput(_pcText); delete[] _pcText; return strOutput; } catch (...) { return std::string(""); } } int CStr2Int(const CString& csStr) { return atoi(CStr2Str(csStr).c_str()); } float CStr2Fl(const CString& csStr) { return (float)atof(CStr2Str(csStr).c_str()); } double CStr2Db(const CString& csStr) { return atof(CStr2Str(csStr).c_str()); } DWORD IpTransform(CString csIp) { if (csIp.GetLength() < 1) return 0; CString _csIp = L""; //Reverse the number of ip address for (int _nLoc = csIp.ReverseFind('.'); _nLoc > 0; _nLoc = csIp.ReverseFind('.')) { _csIp += csIp.Right(csIp.GetLength() - _nLoc - 1) + L"."; csIp = csIp.Left(_nLoc); } _csIp += csIp; return inet_addr(CStr2Str(_csIp).c_str()); } CString IpTransform(const DWORD& dwIp) { unsigned char *_pIp = (unsigned char*)& dwIp; CString _csIP = L""; _csIP.Format(L"%u.%u.%u.%u", *(_pIp + 3), *(_pIp + 2), *(_pIp + 1), *_pIp); return _csIP; } std::string Sbc2Dbc(const std::string& strSbc) { try { int nLen = strSbc.length(); if (nLen <= 0) return std::string(""); int i = 0; int j = 0; unsigned char chBef = '\0'; unsigned char chAft = '\0'; char *pcSbc = new char[nLen + 1]; char *pcDbc = new char[2 * nLen]; memset(pcSbc, 0, nLen + 1); strcpy_s(pcSbc, nLen + 1, strSbc.c_str()); memset(pcDbc, 0, 2 * nLen); for (i = 0; i < nLen; i++) { chBef = pcSbc[i]; chAft = pcSbc[i + 1]; if ((chBef == 0xA3 && 0xC1 <= chAft && chAft <= 0xDA) //English || (chBef == 0xA3 && 0xE1 <= chAft && chAft <= 0xFA)) { pcDbc[j++] = chAft - 0x80; i++; continue; } else if ((chBef == 0xA1) && (chAft == 0xA1)) //Space { pcDbc[j++] = 0x20; i++; continue; } else if ((chBef >= 0x81) && (chBef <= 0xFE) //Chinese && (chAft >= 0x40) && (chAft <= 0xFE)) { pcDbc[j++] = chBef; pcDbc[j++] = chAft; i++; continue; } pcDbc[j++] = chBef; } pcDbc[j] = '\0'; delete[]pcSbc; delete[]pcDbc; return std::string(pcDbc); } catch (...) { return std::string(""); } } /// // // // 2. Split,Replace // // // /// int SplitCStr( const CString& csStr , const CString& csFlag , std::vector 
        
          & vecElement ) { if ( !csStr.GetLength() ) return 0; if ( -1 == csStr.Find( csFlag ) ) { vecElement.push_back( csStr ); return 1; } int _nTimes = 0; CString _csString = csStr + csFlag; //为了分割字符串结尾没有分隔符的字符 for ( int _nLoc = 0 ; -1 != _csString.Find( csFlag , _nLoc ) ; _nLoc = _csString.Find( csFlag , _nLoc ) + csFlag.GetLength() , ++_nTimes ) vecElement.push_back( _csString.Mid( _nLoc , _csString.Find( csFlag , _nLoc ) - _nLoc ) ); return _nTimes; } int SplitString(const std::string& strStr, const std::string& strFlag, std::vector 
         
           &vecElement) { if (!strStr.length()) return 0; if (-1 == strStr.find(strFlag)) { vecElement.push_back(strStr); return 1; } else { vecElement.push_back(strStr.substr(0, strStr.find(strFlag))); return SplitString(strStr.substr(strStr.find(strFlag) + strFlag.length()), strFlag, vecElement) + 1; } } int SplitNames( CString csStr , std::vector 
          
            & vecElement ) { if ( !csStr.GetLength() ) return 0; int _nTimes(0); std::vector 
           
             ::iterator vciElement; CString _csTemp(L""); vecElement.clear(); csStr.Replace( _T(" ") , _T("") ); //Del space while ( -1 != csStr.Find(_T(";;")) ) csStr.Replace(_T(";;"),_T(";")); //去掉连续的英文分号,避免切分出空姓名 while ( 1 == csStr.GetLength() - csStr.ReverseFind(L';') ) csStr = csStr.Left(csStr.ReverseFind(L';') ); //处理末尾多余分号 _nTimes = SplitCStr( csStr , _T(";") , vecElement ); for( vciElement = vecElement.begin() ; vciElement != vecElement.end() ; )//去重 { if ( -1 != _csTemp.Find( *vciElement + L";" )) { vciElement = vecElement.erase(vciElement); if ( vecElement.end() == vciElement ) break; } else { _csTemp += *vciElement + L";"; vciElement++; } } //csStr = _csTemp; return _nTimes; } int ReplaceString( std::string& strStr , const std::string& strOld , const std::string& strNew ) { int _nTimes = 0; for( std::string::size_type _nLoc = 0 ; std::string::npos != strStr.find( strOld , _nLoc ) ; _nLoc = strStr.find( strOld , _nLoc ) + strNew.length() , _nTimes++ ) strStr.replace( strStr.find( strOld , _nLoc ) , strOld.length() , strNew ); return _nTimes; } int ReplaceStringAll( std::string& strStr , const std::string& strOld , const std::string& strNew ) { int _nTimes = 0; while ( std::string::npos != strStr.find(strOld) ) for( std::string::size_type _nLoc = 0 ; std::string::npos != strStr.find( strOld , _nLoc ) ; _nLoc = strStr.find( strOld , _nLoc ) + strNew.length() , _nTimes++ ) strStr.replace( strStr.find( strOld , _nLoc ) , strOld.length() , strNew ); return _nTimes; } /// // // // 3. Generate Date , Serial Number // // // /// /** * @author 2011年 9月 1日 Sai * 2011年10月22日 Sai 将返回类型由string型,变为bool型。 (需要考虑获取时间【已添加获取时间函数】) * 2012年11月16日 Sai 将返回类型由bool型,变为string型;整理优化 * 2012年12月27日 Sai 将返回类型由string型,变为cstring型; * 2013年10月 9日 Sai 将缺省参数默认由0改为1 **/ inline CString GetDate( int nStyle /*= 1 */) { try { SYSTEMTIME _time; GetLocalTime( &_time ); CString _csDate = L""; switch ( nStyle ) { case 0: _csDate.Format( _T("%4d.%.2d.%.2d") , _time.wYear , _time.wMonth , _time.wDay ); break; case 1: _csDate.Format( _T("%4d-%.2d-%.2d") , _time.wYear , _time.wMonth , _time.wDay ); break; default: return CString(L""); } return _csDate; } catch (...) { return CString(L""); } } /** * @author 2012年11月16日 Sai 初始版本 * 2013年10月 9日 Sai 将缺省参数默认由0改为1 **/ inline CString GetTime( int nStyle /*= 1 */) { try { SYSTEMTIME _time; GetLocalTime( &_time ); CString _csTime = L""; switch ( nStyle ) { case 0: _csTime.Format( _T("%.2d:%.2d:%.2d") , _time.wHour , _time.wMinute , _time.wSecond ); break; case 1: _csTime.Format( _T("%.2d-%.2d-%.2d") , _time.wHour , _time.wMinute , _time.wSecond ); break; default: return CString(L""); } return _csTime; } catch (...) { return CString(L""); } } /** * @author 2012年11月16日 Sai 初始版本 * 2013年10月 9日 Sai 将缺省参数默认由0改为1 **/ inline CString GetDateAndTime( int nStyle /*= 1 */) { try { SYSTEMTIME _time; GetLocalTime( &_time ); CString _csDateAndTime = L""; switch ( nStyle ) { case 0: _csDateAndTime.Format( _T("%4d.%.2d.%.2d-%.2d:%.2d:%.2d") , _time.wYear , _time.wMonth , _time.wDay , _time.wHour , _time.wMinute , _time.wSecond ); break; case 1: _csDateAndTime.Format( _T("%4d-%.2d-%.2d:%.2d-%.2d-%.2d") , _time.wYear , _time.wMonth , _time.wDay , _time.wHour , _time.wMinute , _time.wSecond ); break; default: return CString(L""); } return _csDateAndTime; } catch(...) { return CString(L""); } } /** * @author 2012年11月16日 Sai 初始版本 * 2013年02月01日 Sai 添加注释 **/ inline bool GetSerNumByTime( __int64 &ullSerialNum ) { try { SYSTEMTIME _time; GetLocalTime( &_time ); ullSerialNum = _time.wDay; //直接计算会出错,很奇怪,所以单独处理 ullSerialNum *= 1000000000; ullSerialNum += _time.wYear * 10000000000000; ullSerialNum += _time.wMonth * 100000000000; //ullSerialNum += (_time.wDay) * 1000000000; ullSerialNum += _time.wHour * 10000000; ullSerialNum += _time.wMinute * 100000; ullSerialNum += _time.wSecond * 1000; ullSerialNum += _time.wMilliseconds; return true; } catch(...) { return false; } } /** * @author 2012年11月16日 Sai 初始版本 * 2013年02月01日 Sai 添加注释 **/ inline CString GetSerNumByTime() { try { CString _csSerNum(_T("")); SYSTEMTIME _time; GetLocalTime( &_time ); _csSerNum.Format( _T("%.4d") _T("%.2d") _T("%.2d") _T("%.2d") _T("%.2d") _T("%.2d") _T("%.3d") , _time.wYear , _time.wMonth , _time.wDay , _time.wHour , _time.wMinute , _time.wSecond , _time.wMilliseconds ); return _csSerNum; } catch(...) { return _T(""); } } _GCS_END #endif 
            
           
          
         
       
      
      
     
     
    
    
   
   



随笔 - 764 文章 - 3 评论 - 196 CString,string,char*之间的转换) 这三种类型各有各的优点,比如CString比较灵活,是基于MFC常用的类型,安性也最高,但可移植性最差。string是使用STL时必不可少的类型,所以是做工程时必须熟练掌握的;char*是从学习C语言开始就已经和我们形影不离的了,有许多API都是以char*作为参数输入的。所以熟练掌握三者之间的转换十分必要。 以下我用简单的图示指出三者之间的关系,并以标号对应转换的方法。 1 string to CString CString.format("%s",string.c_str()); 2 CString to string string str(CString.GetBuffer(str.GetLength())); 3 string to char * char *p=string.c_str(); 4 char * to string string str(char*); 5 CString to char * strcpy(char,CString,sizeof(char)); 6 char * to CString CString.format("%s",char*); CString的format方法是非常好用的。string的c_str()也是非常常用的,但要注意和char *转换时,要把char定义成为const char*,这样是最安的。 以上函数UNICODE编码也没问题:unicode下照用,加个_T()宏就行了,像这样子_T("%s") 补充: CString 可能是 CStringW/CStringA,在与 string 转换时,如果是 CStringW,还涉及编码转换问题。下面以 CStringA 来说明。 1 string to CString CString.format("%s",string.c_str()); CStringA = string.c_str() 就可以了 2 CString to string string str(CString.GetBuffer(str.GetLength())); GetBuffer 有参数的话,可能导致内部的分配空间动作,要进行后续 ReleaseBuffer 操作。 string = CStringA string = CStringA.GetBuffer(); 3 string to char * char *p=string.c_str(); 4 char * to string string str(char*); 5 CString to char * strcpy(char *,CString,sizeof(char)); 按照 3 风格,这里应该 char * = CStringA; 或者 char *p = CStringA.GetBuffer(); 6 char * to CString CStringA = char * 就可以了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值