字符串反转
#include "stdafx.h" #include<iostream> using namespace std; char*reverse_str(char*str); int _tmain(int argc, _TCHAR* argv[]) { char*str = "abcdefgh"; char*dst = reverse_str(str); cout << dst << endl; system("pause"); return 0; } char*reverse_str(char*str) { char*dst=new char[strlen(str)+1]; *dst = '\0'; while (*str != '\0') { *(--dst) = *(str++); cout << *dst << endl; } return dst; }
atoi
// my_atoi.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; int my_atoi(char*in); int _tmain(int argc, _TCHAR* argv[]) { char*in = "0123h4dfdd"; cout << atoi(in) <<endl; cout << my_atoi(in) << endl; system("pause"); return 0; } int my_atoi(char*in) { int kk = 0; int sum = 0; while (*in <= '9'&&*in >= '0') { int kk=*in-'0'; sum = sum*10+kk; ++in; } return sum; }
编写一个程序实现功能:将两个字符串合并为一个字符串并且输出,用指针实现。
</pre><pre name="code" class="cpp">#include "stdafx.h" #include<iostream> using namespace std; char*my_strcat(char*src, char*dst) { char*p = dst; while (*p != '\0') p++; while (*src != '\0') { *p = *src; p++; src++; } *p = '\0'; return dst; } int _tmain(int argc, _TCHAR* argv[]) { char*src = new char[100]; strcpy(src, "RST"); char*dst = new char[100]; strcpy(dst, "ggggg"); cout << my_strcat(src, dst); system("pause"); return 0; }
子字符串的替换(C语言)
描述:编写一个字符串替换函数,如函数名为 StrReplace(char* strSrc, char* strFind, char* strReplace),strSrc为原字符串,strFind是待替换的字符串,strReplace为替换字符串。
举个直观的例子吧,如:“ABCDEFGHIJKLMNOPQRSTUVWXYZ”这个字符串,把其中的“RST”替换为“gggg”这个字符串,结果就变成了: ABCDEFGHIJKLMNOPQggggUVWXYZ
// StrReplace.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; char*StrReplace(char* strSrc, char* strFind, char* strReplace) { char*p1 = strSrc; char*p2 = strFind; char*p=NULL; bool flag = false; while (*p1 != '\0') { if (*p1 == *p2) { p = p1; while (*p1 == *p2&&*p1 != '\0') { p1++; p2++; if (*p2 == '\0') { flag = true; break; } } } else p1++; if (flag) break; } if (flag) { char*p3=new char[100]; //char*p4 = p3; char*p5 = p1; //while (*p1 != '\0') // *(p3++) = *(p1++); strcpy(p3, p1); //*p3 = '\0'; while (*strReplace != '\0') { *p = *strReplace; p++; strReplace++; } while (*p3 != '\0') { *(p) = *(p3); ++p; ++p3; } *p = '\0'; } return strSrc; } int _tmain(int argc, _TCHAR* argv[]) { char*src = new char[100]; strcpy(src, "ABCDEFGHIJKLMNOPQRSTpVWXYZ"); //src = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";不能直接传const char*类型的值,否则在程序中无法改变值 char*find = new char[100]; //char*find = "RST"; strcpy(find, "RST"); char*replace = new char[100]; strcpy(replace, "ggggg"); //char*replace = "ggggggggg"; cout << StrReplace(src, find, replace) << endl; system("pause"); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014568921/article/details/46849313