6

I've written some code that I believe is very close to the answer of the problem, but I can't seem to properly compare two characters. I don't know how to properly cast them.

I know how to do this using arrays, but I want to know how to do it using pointers.

char *FindToken(char *s,char *t)
{
    while (s)
    {
        //char check = *(char*)s; tried this but it doesn't work
        while(t)
        {
            if (strcmp(s,t)){
                //return s;
                printf("%s", s);
            }
            t++;
        }
        s++;
    }
    return NULL;
}

This is the original problem:

Write a C function called that accepts 2 parameters: a null terminated character array (string) called S in reference to the string to be searched, and a second string parameter called T. The string T is a list of characters (not including the ‘\0’) that are tokens, or characters to be searched for in S. Do not modify either S or T. It will return a character pointer to the position of the first character in T that is found in S, if it is found in S, or NULL otherwise.

For example:

printf("%s", *FindToken(“are exams over yet?”, “zypqt”)); // will display “yet?”
6
  • 1
    Do we need the brackets around t++ in line 12?: (t++);? Commented Apr 10, 2019 at 12:00
  • Check strtok function. I think it going to help you. Commented Apr 10, 2019 at 12:01
  • 1
    strcmp compares the whole strings not characters. Commented Apr 10, 2019 at 12:04
  • 2
    You probably can't use it, but this assignment is to write a version of the standard strpbrk() function, fwiw. Commented Apr 10, 2019 at 12:08
  • @MOehm right sorry Commented Apr 10, 2019 at 12:09

1 Answer 1

7

You were almost close.

With few problems.

  1. When you do (t++), ultimately you are making t to point end of its memory and leading UB.
  2. strcmp is not for comparing char as you wanted.

char *FindToken(char *s,char *t)
{
    while (*s)
    {
        int i = 0;
        //char check = *(char*)s; tried this but it doesn't work
        while(t[i])
        {
            if (*s == t[i])) {
                printf("%s", s);
                return s;
            }
            i++;
        }
        s++;
    }
    return NULL;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@EdHeal Yes even little shorter :). But I've written some code that I believe is very close to the answer of the problem OP wanted to know his mistake in the current code only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.