adding a character to a string on a given place

Started by
2 comments, last by da_cobra 20 years, 2 months ago
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...
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]
What a lovely potential for a buffer overflow =)

-=[ Megahertz ]=-

[edited by - Megahertz on January 24, 2004 6:34:29 AM]
-=[Megahertz]=-
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)

This topic is closed to new replies.

Advertisement