• 0

[C] Copy only Unique elements from string to another


Question

Hi my task is to get the user to input a string and then copy only the unique elements to another string.

For example user enters AABBBACDEEEF in to string1, string 2 prints ABCDEF.

We're not allowed to use pre built functions i.e. stuff from string.h.

This is an extra exercise and I don't have to do it but I'm curious and it's driving me mad so I wondered if any of you could help?

I know I need to test each element in array 1 for duplicates and then only copy one over (I think) or do I copy the first instance of every character in string 1 over to string 2 then check string 2 for duplicates before copying the next character?

Any help would be appreciated, thanks

Link to comment
Share on other sites

16 answers to this question

Recommended Posts

  • 0

I haven't wrote anything yet I'm just trying to figure out the process on paper first.

What I was thinking at first was to use a for loop to cycle through each element in the array and then use another loop to cycle again through each element to compare them, but then this doesn't really achieve anything it would only copy an element if it only occurred once in the string.

Link to comment
Share on other sites

  • 0

I'd do this with a single loop:

for char in string {

search endstring for char

if no match {

insert char to string 2

}

}

Pseudo-code, but I think its logically sound?

Link to comment
Share on other sites

  • 0

^ Thats works, but order of the characters would not be persisted, as only the last instance of each character would be stored, in that order. To the OP: would this be an issue?

Link to comment
Share on other sites

  • 0

I'd do this with a single loop:

for char in string {

search endstring for char

if no match {

insert char to string 2

}

}

Pseudo-code, but I think its logically sound?

Yeah Kinda but if there is a duplicate char I still want to copy it, but only 1 instance of it.

Link to comment
Share on other sites

  • 0

Why don't you sort it. Then loop through the string, copying the first character of a group of characters, then move along the string until you hit a different character. Stop once you have copied '\0'.

Link to comment
Share on other sites

  • 0

it's really easy, make an int array of size 256 (the ascii characters) and iterate through your string, use the char as the array index and add one for every time a character shows up; when you're done just iterate through your int array and add any char which has a count different than 0 to your output.

Link to comment
Share on other sites

  • 0

it's really easy, make an int array of size 256 (the ascii characters) and iterate through your string, use the char as the array index and add one for every time a character shows up; when you're done just iterate through your int array and add any char which has a count different than 0 to your output.

That's one way I was thinking, but there's an even better way to utilize that.

int array[256];
int i = 0;

while (string1[i]) {
    char tmp = string1[i];
    if (!array[tmp]) {
        array[tmp]++;
        strcat(string2, tmp);
    }
    i++;
}

Link to comment
Share on other sites

  • 0

#include <stdio.h>
#include "simpleio.h"
#include <string.h>

int main()
{
	char str1[255];
	char str2[255];
	char *ptr = str2;
	int i = 0;
	int array[256]= {0};

	printf("Enter text: "); getString(str1,254);

	for (i=0;i<strlen(str1);i++)
	{
		array[str1[i]]++;
	}

	for (i=0;i<256;i++)
	{
		if (array[i] > 0)
		{
			*ptr = i;
			ptr++;
		}
	*ptr = '\0';
	}

	printf("%s\n", str2);
	return 0;
}

OK this is what I have come up with, I tried Xilo's method but didn't quite understand it but this seems to work properly and I'm happy with it. Any suggestions on how to improve efficiency?

Oh and thanks for everyone's help :)

Link to comment
Share on other sites

  • 0

Some comments:

- Take strlen out of the loop

- Use '#define's so you don't have the 255/266 magic constants littered around (in C++ it would be better to use a static const int, I don't know if they can be used in c or not)

- If str1 is a '\0' terminated string, you can just increment the pointer until the char is '\0', instead of using strlen

- Its probably just me, but I prefer memset to '= {0}'

Link to comment
Share on other sites

  • 0

My version eliminates the 2nd for loop and combines the two.

It will loop through string 1, just like you have it. It then checks if the count for that char in the array is 0. If it is, it will update the count and add the char to string 2.

...
        for (i = 0; i != '\0'; i++)
        {
                char tmp = str1[i];
                // is this the first occurance of the character?
                if (array[tmp] == 0)
                {
                        // increment the count
                        array[tmp]++;
                        // assign the current character to the 2nd string and increment the pointer
                        *ptr++ = tmp;
                }
        }
        // set the final character to NULL
        *ptr = '\0';
...
}

Link to comment
Share on other sites

  • 0

Thanks again for all the comments, I have amended my code.

Now I ask another favour, just to look over another piece of code I have written, the task the teacher set is the comments in the function. My function works but I feel like it is messy and it was mostly guess work getting it to give the right answers, so any comments would be appreciated :)

    int strfind(char * string1, char * string2)
    {
       /* if string1 contains the substring string2 returns
          the starting position of string2 in string1
          otherwise returns -1
          e.g.  strinc("hello world","wor") returns 6
                strinc("hello world","war") returns -1
       */
       char *ptr1 = string1;
       char *ptr2 = string2;
       int count = 0;

       while (*ptr1 != '\0')
       {
       		if (*ptr1 == *ptr2)
       		{
       			if (*ptr2 != '\0')
       			{
       				while (*ptr1 == * ptr2 && *ptr1 != '\0')
       				{
       					ptr1++;
       					ptr2++; 

       				}

       				if (*ptr2 == '\0')
       				{
       					return count;
       				}

       			}
       		}
       		count++;
       		ptr1++;
       }
       return -1;
    }

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.