Quickie: inserting chars into a char array

Started by
3 comments, last by Fresh 23 years, 4 months ago
Simple question: How do I insert a character into the char array buf, at say a position denoted by the variable current_position (taking domain 0 to strlen(buf))? r. "The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."
Advertisement
quote:Original post by Fresh
Simple question:
How do I insert a character into the char array buf, at say a position denoted by the variable current_position (taking domain 0 to strlen(buf))?
r.



  1. Create a new array that is one char bigger and copy all the chars up to current_pos.
  2. Put in the new char.
  3. Copy the rest of the chars.



----------
Andrew
Fine, but the technicalities perplex me; I imagine it''d be something along the lines of:

I want to insert a char into caption[255];

caption[255],
buf[255], are being used without any indirection as follows:

strncpy(buf, caret_position, caption);
caption += caret_position;
strcat(buf, (char)ascii_key);
strcat(buf, caption);
strncpy(caption, strlen(buf),buf);

The problem is with caption += x - this increases the actual value of the char at its index, and I cant figure out what sort of indirection is needed to make this work. Doesn''t anybody have
some sample code that I can look at?
r.

"The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."
Assuming that "buffer" is the destination buffer whose maximal length is "len" and the first "used" entries has been occupied, this simple C function insert the character "c" at position "position" by shifing the remaining entries.

  <i>int InsertChar(char *buffer, int len, int used, int position, char c){    int i;    for (i = used; i >= position; i--)        buffer[i] = buffer[i - 1];    buffer[i] = c;    return(used + 1);}  


Returns the new amount of entries in "buffer"...

Hope it helps.


Bye,

Karmalaa

---
"Lifting shadows off a dream once broken
She can turn a drop of water into an ocean"


Edited by - karmalaa on November 24, 2000 4:26:43 PM
---[home page] [[email=karmalaa@inwind.it]e-mail[/email]]
Much Obliged.
r.

"The mere thought hadn''t even begun to speculate about the slightest possibility of traversing the eternal wasteland that is my mind..."

This topic is closed to new replies.

Advertisement