【发布时间】:2020-04-22 05:01:55
【问题描述】:
我必须使用一个函数,该函数接受两个字符串和一个整数值,它告诉在第一个字符串中输入第二个字符串的位置。
例如:
String 1 = "I have apple"
String 2 = "an "
position = 6,
输出:
String 1 = "I have an apple"
到目前为止,这是我的代码:
#include <iostream>
using namespace std;
const int SIZE=102;
void insertString(char str1[ ],char str2[ ],int position);
int main()
{
char str1[SIZE], str2[SIZE];
int position,i=0,j=0;
cout<<"Enter string 1 of atmost 50 characters:\n";
cin.getline(str1,SIZE/2);
cout<<"Enter string 2 of atmost 50 characters:\n";
cin.getline(str2,SIZE/2);
cout<<"Enter Position number where String 2 is to be inserted: ";
cin>>position;
while(position<0||position>50)
{
cout<<"Invalid input. Enter a positive Position number less than 51\n"<<
"where String 2 is to be inserted: ";
cin>>position;
}
insertString(str1,str2,position);
cout<<"Modified string 1: "<<str1<<endl;
system("pause");
return 0;
}
/******************************************************************************
Definition of function insertString:
This function takes two C-string in form of character arrays and one integer value
as parameters
It inserts String 2 in String 1 on the required position.
*******************************************************************************/
void insertString(char str1[ ],char str2[ ],int position)
{
char temp[SIZE];
int i,j,countStr2;
for(j=0;j<SIZE&&str2[j]!=0;j++)
countStr2=j;
for(i=position,j=0;i<SIZE,j<=countStr2; i++,j++)
{
temp[i]=str1[i];
str1[i]=str2[j];
}
}
这个逻辑覆盖了字符串1的一些字符,我该怎么办?
任何帮助将不胜感激。
【问题讨论】:
-
你不使用
std::string有什么原因吗? -
我建议现在学习它。使用
char[]是一件非常 C 的事情……否则,您知道问题在于覆盖。所以,您已经创建了一个char temp[SIZE],但您似乎没有正确使用它。将值暂时存储在那里,然后使用它们。 -
有还是没有?使用
std::string,您可以使用insert -
std::string str1 = "I have apple"; std::string str2 = "an"; int position = 6; str1.insert(position, str2); -
请注意,您有
temp,但它在该功能之外的用途是什么?这是一个措辞不佳的赋值,因为当该函数返回时,实际上不会插入任何内容。这就是为什么像这样以C方式做事需要在设计方面多加思考。插入的字符串应该在哪里返回给调用者?以什么形式?一个新的字符串?用户提供的现有缓冲区?复制到str1?您需要告诉我们这些信息。使用std::string,该字符串将被更改,无需提问。
标签: c++ arrays string function