C 替换字符方法
// 444.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include<stdlib.h> #include <string.h> #define MAX_MSG_LENGTH 600 char *strcpy1(char *strDes, char *strSrc){ if(strSrc==NULL) return strDes; //若strSrc为NULL,则抛出异常。 strDes=(char *)malloc(strlen(strSrc)+1); //多一个空间用来存储字符串结束符'\0' char *p=strDes; while(*strSrc!='\0'){ *p++=*strSrc++; } *p='\0'; return strDes; } // 替换字符串中特征字符串为指定字符串 char * ReplaceStr(char *sSrc, char *sMatchStr, char *sReplaceStr) { int StringLen; char caNewString[MAX_MSG_LENGTH]; char *FindPos = strstr(sSrc, sMatchStr); if( (!FindPos) || (!sMatchStr) ) return sSrc; while(FindPos) { memset(caNewString, 0, sizeof(caNewString)); StringLen = FindPos - sSrc; strncpy(caNewString, sSrc, StringLen); strcat(caNewString, sReplaceStr); strcat(caNewString, FindPos + strlen(sMatchStr)); sSrc= strcpy1(sSrc, caNewString); FindPos = strstr(sSrc, sMatchStr); } return sSrc; } int main(int argc, char* argv[]) { char * abc="asdfasdfadfsasdff \336 asdfasd \336 asdf ddd"; char * matchStr="\336"; char * repedStr="455"; printf("\n原先的串%s\n",abc); abc=ReplaceStr(abc,matchStr,repedStr); printf("\n--替换完了之后的串--\n%s\n",abc); char *kk="\336"; //相同的: // printf("\n%s\n","\336");//八进制 // printf("\n%c\n",222);//十进制 // printf("\n%c\n",0xDE);//十六进制 return 0; }
本文来自博客园,作者:aspirant,转载请注明原文链接:https://www.cnblogs.com/aspirant/p/3571517.html