I've been working on a function that takes a string of random characters as parameter (char *scrap
) and forms a meaningful sentence or a name out of it by matching it with letters from another string (char *name
) that also passed into its parameters, if no matching characters in enough quantity is found function will return 1. But the function iterates through both arrays with index order, so if target string's first character is in the end of the scrap
it only writes down that character but I want it to be able to write down the entire string if all of its characters are present in enough quantity in that scrap
array if not it must return a blank array. the function is also case sensitive so if all letters in name is also present in enough quantity but differentiate in case it will still return blank array.
Here's an example of the output I want:
name[] = "jan suk"
scrap[] = "ansukj"
Expected output = "jan suk"
Real output = "j"
name[] = "JAN SUK"
scrap[] = "jan suk"
expected output = blank array
real output = blank array
or
name[] = "jan suk"
scrap[] = "ju"
expected output = blank array
real output = "j"
name[] = "jan suk"
scrap[] = "skjuna"
Expected output = "jan suk"
Real output = "ja"
name[] = "peter"
scrap[] = "ertP"
expected output = blank array
real output = blank array
The current codes output is "j" and "ja" because function start iteratively checks from the first index to the end and although rest of the letters are also in name array, function still can't get past the first index.
First thing I tried is to iterate backwards once the function finds a match but it still doesn't serves the purpose I wanted:
char *scramble_words(char *name, char *scrap)
{
int n = 0;
int s = 0;
size_t len = strlen(name);
size_t len2 = strlen(scrap);
char *new = malloc((len + 1) * sizeof(char));
while(n < len && s < len2)
{
if(name[n] == ' ')
{
new[n] = name[n];
n++;
}
if(name[n] == scrap[s])
{
new[n++] = scrap[s++];
for(int j = s; j < len2 - s;j-- && n < len)
{
if(name[n] == scrap[j])
{
new[n++] = scrap[j];
}
}
}
else if(name[n] != scrap[s])
{
s++;
}
}
new[len] = '\0';
return new;
}
for(int j = s; j < len2 - s;j-- && n < len)
feels very wrong!J
in the input should become a lower-casej
in the output. Is this because thescrap
array contains a lower-casej
, but not a capital-caseJ
? Please edit the question to clarify this.