C++: Insert Char to a String

Inserting characters into a string

Yes, you will need to write your own function for that.

Note that a string in C is a char[], i.e. an array of characters, and is of fixed size.

What you can do is, create a new string that serves as the result, copy the first part of the subject string into it, append the string that goes in the middle, and append the second half of the subject string.

The code goes something like,

// inserts into subject[] at position pos
void append(char subject[], const char insert[], int pos) {
char buf[100] = {}; // 100 so that it's big enough. fill with zeros
// or you could use malloc() to allocate sufficient space
// e.g. char *buf = (char*)malloc(strlen(subject) + strlen(insert) + 2);
// to fill with zeros: memset(buf, 0, 100);

strncpy(buf, subject, pos); // copy at most first pos characters
int len = strlen(buf);
strcpy(buf+len, insert); // copy all of insert[] at the end
len += strlen(insert); // increase the length by length of insert[]
strcpy(buf+len, subject+pos); // copy the rest

strcpy(subject, buf); // copy it back to subject
// Note that subject[] must be big enough, or else segfault.
// deallocate buf[] here, if used malloc()
// e.g. free(buf);
}

Working example here

Insert char into char array C (string)

Assuming:

char array[7] = "anana";

Then:

memmove(array+1, array, 6);
array[0] = 'B';

The memmove function is specifically for cases where the data movement involves an overlap.

Inserting char string into another char string

char * strA = "Blahblahblah", * strB = "123", strC[50];
int x = 4;
strncpy(strC, strA, x);
strC[x] = '\0';
strcat(strC, strB);
strcat(strC, strA + x);
printf("%s\n", strC);

Explanation:

  1. You declare the two strings you will be joining, plus a third string into which you will put them.
  2. You declare an integer to tell the program after how many characters you wish to insert the second string into the first.
  3. The strncpy function copies the first x characters into strC. You have to add the null ('\0') character at the end, otherwise you'll probably get rubbish.
  4. Strcat to copy the second string.
  5. Another strcat to copy the remaining part of the first string (strA + x).

Hope that helps.

Remark: remember to make strC long enough to contain both strA and strC, otherwise you'll produce a segmentation fault. You may do this by declaring the string as an array, like in my example.

How to insert an extra character in a string in C

In order to work you must implement your replace function correctly

It should be like:

void replace(char a[],char b[])
{
int idxA = 0, idxB = 0;

for(idxA;idxA<strlen(a);idxA++, idxB++)
{
b[idxB] = a[idxA];
if(a[idxA]=='a')
{
idxB++;
b[idxB]=a[idxA];
}
}

b[idxB] = '\0';
printf("%s\n",b);
}

But you must ensure b has enough space to hold the complete string. For example, you can reserve twice the size of a, the worst case when array a has all a characters

C++: insert char to a string

There are a number of overloads of std::string::insert. The overload for inserting a single character actually has three parameters:

string& insert(size_type pos, size_type n, char c);

The second parameter, n, is the number of times to insert c into the string at position pos (i.e., the number of times to repeat the character. If you only want to insert one instance of the character, simply pass it one, e.g.,

someString.insert(somePosition, 1, myChar);

Inserting String into String in C

Not going to sugar coat it. This code is a mess. The task you're trying to accomplish is easiest if you simply

  • Copy from [0..min(n, lengthS1)) (note exclusivity of right side) from s1[] to your target.
  • Append s2[] to the target.
  • Append s1[min(n, lengthS1)] through s1[lengthS1] to the target.
  • Terminate the string
  • That's it.

And above all, the target must be able to accommodate both strings and a nulchar terminator, which your target buffer does not do (it is short by one character).

There is no need for nested for-loops. And yours is broken regardless as it is walking on its own indexing variables.

#include <stdio.h>

size_t length(const char s[])
{
const char *end = s;
while (*end)
++end;
return end - s;
}

void insert(const char s1[], const char s2[], int n)
{
size_t lengthOfS1 = length(s1);
size_t lengthOfS2 = length(s2);
size_t pos = (n < lengthOfS1) ? n : lengthOfS1;
size_t i;

// declare VLA for holding both strings + terminator
char s1Copy[lengthOfS1 + lengthOfS2 + 1];

// put in part/full s1, depending on length
for (i=0; i<pos; ++i)
s1Copy[i] = s1[i];

// append s2
for (i=0; i<lengthOfS2; ++i)
s1Copy[pos+i] = s2[i];

// finish s1 if needed.
for (i=pos; i<lengthOfS1; ++i)
s1Copy[i+lengthOfS2] = s1[i];

// termiante string
s1Copy[lengthOfS1 + lengthOfS2] = 0;

puts(s1Copy);
}

int main()
{
char ab[] = "Chicken and Chips";
char b[] = "Scampi";
insert(ab, b, 0);
insert(ab, b, 7);
insert(ab, b, 100);
}

Output

ScampiChicken and Chips
ChickenScampi and Chips
Chicken and ChipsScampi

Summary

If you're not sure what is going on, the last thing you should be doing is writing more code. Rather, stop coding, get some paper and a writing instrument, and rethink the problem.

C++ insert char into string

here's the prob How do I insert a space in front and after the t, in
the May string

Replace

may.insert(5, ' ');

with

may.insert(5, " ");

You need use double quotes for String, not single quotes which mean char.

Update

It seems that your requirement is to do the insert at two places at the same time. Try following:

may.insert(4, " ").insert(6, " ");

how to add char to end of string in C?

In C you need to make sure the destination variable has enough memory to store the stuff you want to copy there.

strcat needs a string (char *).

Here is my fixed version of your code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void append(char *s, char c)
{
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}

int main()
{
char str[] = "hello world!";
int len = strlen(str);
char resultat[len * 3];
resultat[0]='\0';
printf("******* case 01 *******\n");
char tmp[2];
tmp[1] = '\0';
for (int i = 0; i < len; i++)
{
tmp[0] = str[i];
strcat(resultat, tmp);
}
printf("resultat = %s\n", resultat);
printf("******* case 02 *******\n");
for (int i = 0; i < len; i++)
{
append(resultat, str[i]);
}
printf("resultat = %s\n", resultat);
return 0;
}

Insert a string to another string in C

This loop

for(i=lenght1, j=0; i<finalLenght; i++, position++, j++)
{
string[i] = string[position];
string[position] = insert[j];
}

is incorrect because independent on the given position all characters from the source string stating at position position are written after the end of the source string.

Also the function insertString should be declared like

char * insertString(char string[], const char insert[], size_t position);

Here is a demonstrative program that shows how the function can be implemented.

#include <stdio.h>

size_t numOfChars( const char s[] )
{
size_t n = 0;

while ( s[n] != '\0' ) ++n;

return n;
}

char * insertString( char s1[], const char s2[], size_t pos )
{
size_t n1 = numOfChars( s1 );
size_t n2 = numOfChars( s2 );

if ( n1 < pos ) pos = n1;

for ( size_t i = 0; i < n1 - pos; i++ )
{
s1[n1 + n2 - i - 1] = s1[n1 - i - 1];
}

for ( size_t i = 0; i < n2; i++)
{
s1[pos+i] = s2[i];
}

s1[n1 + n2] = '\0';

return s1;
}

int main(void)
{
enum { N = 20 };
char s1[N] = "123";

puts( insertString( s1, "AB", 0 ) );

char s2[N] = "123";

puts( insertString( s2, "AB", 1 ) );

char s3[N] = "123";

puts( insertString( s3, "AB", 2 ) );

char s4[N] = "123";

puts( insertString( s4, "AB", 3 ) );

return 0;
}

The program output is

AB123
1AB23
12AB3
123AB


Related Topics



Leave a reply



Submit