Originally Posted by
shoobsie
p.s. is there anyway of deleting the data in a string??
for example like a reverse
then i can have a string with the unchanging stuff and take it away from the incoming string to leave me the changed (random) stuff?
one way to do it would be to create a new string, copy everything you want to keep into the new string, and then either get rid of the old string, or replace the old one with the new one.
String editing is difficult because, remember, the way it is stored in memory is usually like this:
Code:
[H][e][l][l][o][ ][w][o][r][l][d][!][\0]
so, if you weant to get rid of 'world' and keep hello, it's easy, all you have to do is insert a null character (string terminator) in position 5 (the space), but if you want to get rid of "Hello " then probably the easiest way is to make a new string.
you could also make your own struncat function
Code:
#include <stdio.h>
#include <string.h>
//return values: -1 for a failure, 0 or a positive number for the
// number of times it removed 'remove' from 'string'
int struncat(char* string, char* remove)
{
if(!string || !remove) return -1;
char* temp=0;
temp = (char*)malloc(strlen(string));
//make sure it was allocaed
if(!temp) return -1;
char* s = string;
char* t = temp;
int x=0;
while(*s != '\0') {
if(!strncmp(s, remove, strlen(remove))) {
s += strlen(remove);
x++;
} else {
*t = *s;
t++;
s++;
}
}
*(t++) = '\0';
strcpy(string, temp);
return x;
}
int main(int argc, char* argv[])
{
char string[1024];
char remove[32];
strcpy(string, "Hello, World, Hello!");
strcpy(remove, "Hello");
if(struncat(string, remove)>=0) printf("struncat was successful.\n");
printf("%s\n", string);
return 0;
}
Code:
output:
struncat was successful.
, World, !
something like that.. not sure if that actually works for you, but check it out.