编写递归函数char *itostr (int n,char *string)

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

char *itostr(int n, char *string)
{
	static int i = 0;
	if (n < 0)				//当输入为负数时需要加上‘-’
	{
		n = -n;
		i++;
		string[0] = '-';
	}

	if (n / 10 == 0)	//n此时只剩一位数即为最后一位,需要在末尾加上‘\0’
	{
		string[i] = n + '0';
		string[i + 1] = '\0';
	}
	else
	{
		itostr(n / 10, string);//利用整除取数进行递归调用
		i++;
		string[i] = (n % 10) + '0';//利用模10取余获取最右位数字并转换成字符
		string[i + 1] = '\0';//末尾需要加上‘\0’表示结束

	}
	return string;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int n;
	cout << "please input the number: " << endl;
	cin >> n;
	char str[100];
	itostr(n, str);
	cout << str << endl;
	return 0;
}

,该函数将整数n转换为十进制表示的字符串。

下面是完整代码: ```c++ #include <iostream> #include <cstring> using namespace std; char *ReplaceString(char *str, char *s1, char *s2); int main() { char str[100], s1[10], s2[10]; cin >> str >> s1 >> s2; char *result = ReplaceString(str, s1, s2); cout << result << endl; delete[] result; return 0; } char *ReplaceString(char *str, char *s1, char *s2) { char *newstr = new char[strlen(str) + 1]; char *ptr = strstr(str, s1); if (ptr == NULL) { strcpy(newstr, str); return newstr; } int len1 = strlen(s1); int len2 = strlen(s2); int len = ptr - str; strncpy(newstr, str, len); newstr[len] = '\0'; strcat(newstr, s2); strcat(newstr, ptr + len1); char *tmp = ReplaceString(newstr + len + len2, s1, s2); strcat(newstr, tmp); delete[] tmp; return newstr; } ``` 思路说明: 1. 首先定义一个 `ReplaceString` 函数,输入参数包括待替换的字符串 `str` 和两个字符串 `s1` 和 `s2`。 2. 在函数中,使用 `strstr` 函数查找 `str` 中第一个出现 `s1` 的位置,并将其指针保存在 `ptr` 中。 3. 如果找不到 `s1`,则直接将 `str` 复制到新字符串 `newstr` 中,并返回。 4. 否则,先将 `ptr` 前面的字符串复制到 `newstr` 中,并在 `newstr` 后面添加 `s2`。 5. 再递归调用 `ReplaceString` 函数,将 `newstr` 中 `ptr` 后面的字符串传入,直到找不到 `s1` 为止。 6. 最后将递归得到的字符串拼接到 `newstr` 后面,并返回 `newstr`。 7. 在主函数中,调用 `ReplaceString` 函数进行替换,并输出结果。注意,需要使用 `delete[]` 释放 `newstr` 的内存空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值