版权声明:本文为博主原创文章 https://blog.csdn.net/snowy19130140/article/details/52157090
1.字符串的替换
#include <iostream>
using namespace std;
void strcopy(char *des, char *src) //字符串的复制
{
while (*des++ = *src++);
}
char* mystrcat(char *src1, char *src2, char *res) //字符串的连接
{
int src1_len = strlen(src1);
int src2_len = strlen(src2);
res = new char[src1_len + src2_len];
for (int i = 0; i < src1_len; i++)
{
res[i] = src1[i];
}
for (int i = 0; i < src2_len; i++)
{
res[i + src1_len] = src2[i];
}
res[src1_len + src2_len] = '\0';
return res;
}
char* StrReplace(char *strSrc, char *strFind, char *strReplace)
{
int strFind_len = strlen(strFind);
int strReplace_len = strlen(strReplace);
int i;
for (i = 0; i <strlen(strSrc); i++)
{
int strcompare = strncmp(strSrc + i, strFind, strFind_len);
if (strcompare == 0)
{
int strSrc_len = strlen(strSrc);
int remainlen = strSrc_len - i - strFind_len;
char *temp = new char[remainlen]; //存储strSrc的strFind之后的后部分的字符
strcopy(temp, strSrc + i + strFind_len);
cout << "temp:::" << temp << endl;
char *result = new char[i]; //存储strSrc的strFind之后的前部分的字符
for (int j = 0; j < i; j++)
result[j] = strSrc[j];
result[i] = '\0'; //这个表示字符串的结束,很重要!!!
char *result1 = new char[i + strReplace_len]; //result1:用于存储strSrc在strFind的前部分的字符以及strReplace
result1 = mystrcat(result, strReplace, result1);
cout << ".............." << result1 << endl;
strSrc = new char[i + strReplace_len + remainlen];
strSrc = mystrcat(result1, temp, strSrc); //用于存放替换后的字符
strSrc[i + strReplace_len + remainlen] = '\0'; //标识字符的结束
// StrReplace(newstrSrc, strFind, strReplace);
}
}
return strSrc;
}
int main()
{
char *strSrc = "RSTABCDEFGHIJKLMNOPQRSTUVWRSTXYZRST";
char *strFind = "RST";
char *strReplace = "12345";
// StrReplace(strSrc, strFind, strReplace);
int n = strlen(strSrc);
cout << n << endl;
strSrc = StrReplace(strSrc, strFind, strReplace);
cout << endl;
cout << strSrc << endl;
cout << endl;
/*用于做测试子过程部分的代码
char *res1 = new char[strlen(strFind)];
strcopy(res1, strFind);
cout << res1 << endl;
char *res = new char[strlen(strFind) + strlen(strReplace)];
res = mystrcat(strFind, strReplace, res);
res[strlen(strFind) + strlen(strReplace)] = '\0';
cout << res << endl;
*/
system("pause");
return 0;
}
2.字符串的反转
把”cba” 称为 “abc”的反转串
public class ReverseString {
public static String reverse(String s){
if (s.length() < 2 || s == null)
return s;
else
return reverse(s.substring(1)) + s.charAt(0);
}
public static void main(String[] args){
String s = "123456";
String ss = reverse(s);
System.out.println(ss);
}
!后面会陆续更新这个课题的