專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

C++中用memcpy()函數(shù)復(fù)制字符串的正確方法

作者:黃石磊   來源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2014年03月05日   【字體:
//對字符最容易忽視的是字符串結(jié)尾會(huì)默認(rèn)添加一個(gè)不可見的‘0\’
//因此用memcpy()函數(shù)對字符串復(fù)制時(shí)容器一定要多申請一個(gè)字節(jié)。
//如:char* p1="copy";要想把其copy到另一個(gè)空間中必須申請5Byte的空間:
//做法:char *p2=(char*)melloc(5);memcpy(p2,p1,4);;p2[5]='0\';至此完成復(fù)制;
#include "stdafx.h"
#include "string.h"
#include "malloc.h"
 
 int Findsub(char *all,char *sub)
{
   int count=0;
   int len1=strlen(sub);
 
   char *buffer=(char *)malloc(len1+1);//中間量內(nèi)存的申請
 
   while(*(all+len1-1)!='\0')
   {
     memcpy(buffer,all,len1);//截取,存入buffer
buffer[len1]='\0';    
if(strcmp(buffer,sub)==0)
{
  count++;
  all+=len1;
  //all++;
}
else
{
      all++;
}
   }
 
   free(buffer);
   return count;
 

}

int _tmain(int argc, _TCHAR* argv[])
{
 
char *a="aaaabaaaaaabaa";
char *b="aba";
    int len=Findsub(a,b);
    printf("------------%d\n",len);
return 0;
}

關(guān)閉窗口

相關(guān)文章