500分求一道插入字符串的c++题 考试呢 在线等
来源:百度知道 编辑:UC知道 时间:2024/07/02 06:36:24
编函数
char* insert(const char* str1,const char* str2,int position)
实现将字符串str2插入到str1指定位置position
char* insert(const char* str1,const char* str2,int position)
实现将字符串str2插入到str1指定位置position
#include <iostream>
#include <string>
using namespace std;
char *insert(char *str1, const char *str2, int position)
{
int i;
int len1 = strlen(str1);
int len2 = strlen(str2);
for (i = len1; i >= position; i--)
str1[i + len2] = str1[i];
for (i = position; i < position + len2; i++)
str1[i] = str2[i - position];
return str1;
}
int main()
{
char str1[100] = "abcde";
char str2[100] = "edf";
cout << insert(str1, str2, 1) << endl;
}
using namespace std;
// 这里假定position从1开始, 而且str1前的const应该去掉
char* insert(char* str1,const char* str2,int position)
{
int i, len1 = strlen(str1), len2 = strlen(str2), pos = --position;
if (pos < 0 || pos >= len1)
{
cerr << "Parametor is invalid." << endl;
return NULL;
}