Archived

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

da_cobra

adding a character to a string on a given place

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