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: anull
terminated character array (string) called S in reference to the string to be searched, and a second string parameter calledT
. Thestring T
is alist of characters
(not including the ‘\0’) that are tokens, or characters to be searched for inS
. Do not modify eitherS
orT
. It willreturn
a character pointer to the position of the first character inT
that is found inS
, if it is found inS,
orNULL
otherwise.
For example:
printf("%s", *FindToken(“are exams over yet?”, “zypqt”)); // will display “yet?”
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.
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.
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.
You were almost close.
With few problems.
(t++)
, ultimately you are making t
to point end of its memory and leading UB.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With