-
Using string functions
Hello
i was wondering if someone can help me code a little bit, I understand how some of it works, and ill show what i have, I just dont know how to put this work in a loop. Thanks
If in starts with "abc32fe5v" it should end up with only alpha characters so Out should = "abcfev"
alpha - character array stores the eniter alphabet
1. strspn("abc32fe5v",Alpha) gives 3
2. strcpy the first 3 chars of "abc12de6x" to Out
3. strcspn("32fe5v",Alpha) gives 2, so skip over the net 2 chars of "21fe5v"
1. strspn("fe5v",Alpha) gives 2
2. strcpy the first 2 chars of "fe5v" to Out
3. strcspn("5v",Alpha) gives 1 so skip over 1 chars of "5v"
1. strspn("v",Alpha) gives 1
2. strcpy the first 1 char of "v" to Out
3. strcspn("",Alpha) gives 0 so skip over 0 chars of ""
loop ends because In is finished
-
Man thats really complicating it, do you have to use string functions?
You would be better processing it a character at a time.
A couple of lines of code in a while loop and your there.
Code:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char in[] = "abc32fe5v";
char out[7];
char *p, *q;
p = in;
q = out;
// all processing done here
while(*p)
{
if(isalpha(*p)) // isalpha tests for a letter
*q++ = *p; // store letter in out
p++;
}
*q = '\0'; // ensure there is a null on the end of new string
printf("%s", out);
return 0;
}
You could use subscripts for the arrays if you are unfamiliar with pointers.
-
thanks, I know it would be eaiser however, it requires the use of these functions
-
Here's one way.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//alpha - character array stores the eniter alphabet
char *Alpha = "abcdefghijklmnopqrstuvwxyz";
int main(void)
{
char *original = "abc32fe5v";
char Out[80] = "";
size_t alpha_count;
char *p;
p = original;
while (*p != '\0')
{
alpha_count = strspn(p,Alpha);
printf("alpha_count:%d\n",alpha_count);
strncat(Out,p,alpha_count);
p += alpha_count;
printf("p:%s\n",p);
p += strcspn(p,Alpha);
printf("p:%s\n",p);
getchar();
}
printf("Out:%s\n",Out);
return 0;
}
-
thank you very much for your help, it works like a charm.....