Hello.

i wrote a program to do the following:

Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.

This is what i tried:

void trimString()
{
	char s1[] = "hello world";
	char s2[] = "el";
	int i, j;

	for (i = 0; i < (signed)strlen(s1); i++) {
		for (j = 0; j < (signed)strlen(s2); j++) {
			if (s1[i] == s2[j]) {
				s1[i] = -1;
				break;
			}
		}
	}
	for (i = 0, j = 0; i < (signed)strlen(s1); i++) {
		if (s1[i] != -1) {
			s1[j] = s1[i];
			j++;
		}
	}
	s1[j] = '\0';
	printf("\nString is%s", s1);
}

Can i further improve it in any way?

Thanks.

One way to do it is to use another character array to copy all the characters in s1 that are not in s2.

void trimString()
{
   char s1[] = "hello world";
   char s2[] = "el";
   char s3[255] = {0};
   size_t sz1 = strlen(s1);
   size_t j = 0;
   for(size_t i = 0; i < sz1; i++)
   {
       if( !strchr(s2,s1[i]) )
          s3[j++] = s1[i];
   }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

@AncientDragon

Thanks for the reply.

Well, doesnt

if( !strchr(s2,s1[i]) )

take same time as

for (j = 0; j < (signed)strlen(s2); j++) {
	if (s1[i] == s2[j]) {
		s1[i] = -1;
		break;
	}
}

i was hoping to make the running time better.


Can i further improve it in any way?

Thanks.

Yes. See the comments I added:

void trimString()
{
	char s1[] = "hello world";
	char s2[] = "el";
	int i, j;

	/* Do not use strlen() as a loop parameter.  
	   Use it to load a variable before the loop and use 
	   the variable in the loop definition */
	/* Why are you casting the value to signed? Define the loop 
	   parameter variables as unsigned if you think it's necessary */
	for (i = 0; i < (signed)strlen(s1); i++) {
		for (j = 0; j < (signed)strlen(s2); j++) {
			if (s1[i] == s2[j]) {
				s1[i] = -1;   // this is good
				break;
			}
		}
	}
	for (i = 0, j = 0; i < (signed)strlen(s1); i++) {
		if (s1[i] != -1) {
			s1[j] = s1[i];
			j++;
		}
	}
	s1[j] = '\0';
	printf("\nString is%s", s1);
}

>>take same time as

Not necessarily, depending on how the compiler implements strchr() function. calling strlen() on every loop iteration is very very time consuming and I doubt any compiler will implement strchr() with that. On Intel compatible x86 processors compilers can use a processor instruction to do it.

Edited 6 Years Ago by Ancient Dragon: n/a

This question has already been answered. Start a new discussion instead.