简体   繁体   中英

How to insert a string at x position in another string?

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.

#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;
}

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 `\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;
}

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;
}

LIVE DEMO


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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM