英文:
How to insert a string at x position in another string?
问题
以下是已翻译的代码部分:
我必须使用一个接受两个字符串和一个整数值的函数,该整数值告诉第二个字符串要插入到第一个字符串的位置。
例如:
String 1 = "I have apple"
String 2 = "an "
position = 6
输出:
String 1 = "I have an apple"
这是我的代码,到目前为止:
```cpp
#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的一些字符。我应该怎么办?
任何帮助将不胜感激。
<details>
<summary>英文:</summary>
I have to use a function that takes two strings and one integer value that tell the position at which the second string is to be entered in the first.
For Example:
String 1 = "I have apple"
String 2 = "an "
position = 6,
Output:
String 1 = "I have an apple"
Here's my code, so far:
#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];
}
}
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
</details>
# 答案1
**得分**: 2
```cpp
#include <cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e) ended by `
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
</details>
# 答案1
**得分**: 2
```cpp
#include <cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e) ended by `\0` and inserts str2 in str1 at the specified position in a newStr, then returns the new string as a pointer*/
char* insertString(const char str1[], const char str2[], const int& position)
{
int shiftedPos = position - 1;
int str2Size = strlen(str2);
int str1Size = strlen(str1);
int newSize = str2Size + str1Size + 1;
char* newStr = new char[newSize];
for (int i = 0; i < shiftedPos; i++) newStr[i] = str1[i];
for (int i = 0; i < str2Size; i++) newStr[shiftedPos + i] = str2[i];
for (int i = 0; i < newSize; i++) newStr[shiftedPos + str2Size + i] = str1[shiftedPos + i];
newStr[newSize] = '\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout << insertString(str1, str2, 8);
return 0;
}
` and inserts str2 in str1 at the specified position in a newStr, then returns the new string as a pointer*/
char* insertString(const char str1[], const char str2[], const int& position)
{
int shiftedPos = position - 1;
int str2Size = strlen(str2);
int str1Size = strlen(str1);
int newSize = str2Size + str1Size + 1;
char* newStr = new char[newSize];
for (int i = 0; i < shiftedPos; i++) newStr[i] = str1[i];
for (int i = 0; i < str2Size; i++) newStr[shiftedPos + i] = str2[i];
for (int i = 0; i < newSize; i++) newStr[shiftedPos + str2Size + i] = str1[shiftedPos + i];
newStr[newSize] = '
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
</details>
# 答案1
**得分**: 2
```cpp
#include <cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e) ended by `\0` and inserts str2 in str1 at the specified position in a newStr, then returns the new string as a pointer*/
char* insertString(const char str1[], const char str2[], const int& position)
{
int shiftedPos = position - 1;
int str2Size = strlen(str2);
int str1Size = strlen(str1);
int newSize = str2Size + str1Size + 1;
char* newStr = new char[newSize];
for (int i = 0; i < shiftedPos; i++) newStr[i] = str1[i];
for (int i = 0; i < str2Size; i++) newStr[shiftedPos + i] = str2[i];
for (int i = 0; i < newSize; i++) newStr[shiftedPos + str2Size + i] = str1[shiftedPos + i];
newStr[newSize] = '\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout << insertString(str1, str2, 8);
return 0;
}
';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout << insertString(str1, str2, 8);
return 0;
}
英文:
#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
Another code to perform exactly as you wanted
#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='\0';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='\0';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
答案2
得分: 1
如果你必须实现void insertString(char str1[], char str2[], int position)
函数,你没有太多选择。
其中一个可能的解决方案是将第一个字符串中的字符向右移动,以便插入第二个字符串。
这种方法可能如下所示:
void insertString(char str1[], char str2[], int position) {
const int len1 = strlen(str1);
const int len2 = strlen(str2);
// 首先,将给定位置之后的所有字符向右移动`len2`个位置:
for (int i = 0; i < len1 - position; ++i) {
str1[len1 - i - 1 + len2] = str1[len1 - i - 1];
}
// 然后在给定位置插入第二个字符串:
for (int i = 0; i < len2; ++i) {
str1[position + i] = str2[i];
}
// 确保创建一个新的终止符,因为
// 第一个循环中的终止符已被覆盖
str1[len1 + len2 + 1] = 0;
}
注意,这是潜在的不安全操作!如果str1
数组中没有足够的空间来存储另外strlen(str2)
个字符,这将导致缓冲区溢出。
更安全的选项是在堆上为新的连接字符串分配一个新的缓冲区,但是出于作业的考虑,这应该足够了。
由于你正在使用C ++,在任何生产代码中,你应该完全避免这种方法,可以使用std::string
等替代字符数组。但我已经在评论中看到你目前还不能使用它。
英文:
If you have to implement the void insertString(char str1[ ],char str2[ ],int position)
function, you don't have many options here.
One of the possible solutions is to shift the characters in the first string to the right to make space for the second string to be inserted there.
Such an approach might look like this:
void insertString(char str1[], char str2[], int position) {
const int len1 = strlen(str1);
const int len2 = strlen(str2);
// First, shift all the characters from the given position to the right by `len2` positions:
for (int i = 0; i < len1 - position; ++i) {
str1[len1 - i - 1 + len2] = str1[len1 - i - 1];
}
// Then insert the second string in the given position:
for (int i = 0; i < len2; ++i) {
str1[position + i] = str2[i];
}
// Make sure to create a new terminator since the
// previous one got overwritten by the the first loop
str1[len1 + len2 + 1] = 0;
}
<kbd>LIVE DEMO</kbd>
Note, that this is potentially insecure! If there is not enough space in the str1
array to store another strlen(str2)
characters, it will lead to a buffer overflow.
Way more secure option would be to allocate a new buffer for your new concatenated string on the heap, but for the sake of your assignment, this should suffice.
Since you're using C++, you should avoid this approach altogether in any production code, replacing char arrays with std::string
, for example. But I've already read in the comments that you can't use it just yet.
答案3
得分: 1
假设您可以使用<string>
,那么我会使用std::string::substr:
#include <string>
std::string originalString = "I have apple"; // 原始字符串
std::string insert = " an "; // 在新单词插入前面添加的空格
int position = 6; // 新单词将插入的索引位置
int remainingStringSize = originalString.length() - position - 1; // 计算从插入位置开始剩余的字符数
std::string combinedString = originalString.substr(0, 6) + insert + originalString.substr(position + 1, remainingStringSize); // 结果组合字符串
注意事项,您显然需要检查以下内容:
- 插入位置的索引是否在原始字符串的长度范围内
- 剩余字符数是否大于0
英文:
Assuming you can use <string>
, then I would put std::string::substr to use:
#include <string>
std::string originalString = "I have apple"; // original string
std::string insert = " an "; // added space beforehand for the new word to be inserted
int position = 6; // index where the new word would be inserted
int remainingStringSize = originalString.length() - position - 1; // count how many characters remain from the position you're inserting
std::string combinedString = originalString.substr(0, 6) + insert + originalString.substr(position +1, remainingStringSize); // resulting combined string
Words of caution, you obviously would need to check the following:
- That index position is within the length of the original string where you wish to insert
- That the remaining # of characters is more than 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论