Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an array of characters in a string

Tags:

c

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?”
like image 528
anon Avatar asked Apr 10 '19 11:04

anon


People also ask

How do I get an array of characters from a string?

char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.

How do I find a specific character in a string array in Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Is an array of character a string?

String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char. Strings are immutable. Character Arrays are mutable.


1 Answers

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;
}
like image 129
kiran Biradar Avatar answered Sep 20 '22 05:09

kiran Biradar