• Advertisement

Archived

This topic is now archived and is closed to further replies.

adding a character to a string on a given place

This topic is 5205 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How would I add a character to a string on a given place? I need to ask the user for a directory. But when the user enters : "c:\test", I need to change it to "c:\\test". So I need to add a "\" on the 4rd position. I already searched for a function, didn''t found one. Now I try to make my own function that does this but I just can''t figure it out for now. Maybe some1 can help me here? thanx in advance...

Share this post


Link to post
Share on other sites
Advertisement
Make a new empty string.. copy element by element, and if that copied element is a '\', copy an extra one into the new string. After you're done.. copy the new string back onto the old string..

int i = 0;
int j = 0;
char string1[] = "C:\programming\c\test";
char string2[50];

while (string1[i] != '\0') {
string2[j] = string1[i];
if (string1[i] == '\') {
++j;
string2[j] = '\';
}
++i;
++j;
}
string2[j] = '\0';

// string2 now equals "C:\\programming\\c\\test" and is null terminated.

// to copy back into your old string, loop through it again.

i = 0;
while (string2[i] != '\0') {
string1[i] = string2[i];
++i;
}
string1[i] = '\0';


You could shorten it a little by including the increments inside the array assignment statements.. but this is easier to read. You could use some cstring functions, but this is easy enough.

(silencer)

[edited by - -silencer- on January 24, 2004 6:24:29 AM]

Share this post


Link to post
Share on other sites
Should always test for overflow.. but I wasn''t about to code it without the specifics of his original string lengths..
Next time I''ll write that function using linked lists.. no overflow.

(silencer)

Share this post


Link to post
Share on other sites

  • Advertisement