In: Computer Science
Create C function for String.c and Strings.h that
#include <string.h>
/* substring - return a pointer to the substring beginning at
the iPos-th position.
* If iPos is out-of-range, return (char*)NULL
*/
char* substring(char* str, int iPos);
/* charPosition - return the position of the first occurance of
c in str.
* If c not present, return -1
*/
int charPosition(char* str, char c);
required functions
char* substring(char* str, int iPos)
{
int i=0;
while(str[i]!='\0') /* string is terminated with '\0' in C. traverse string */
{
if(i == iPos) /* if index is same as position passed to function then return address of that charcter*/
return &str[i];
i++;
}
return (char*)NULL; /* if control comes out of the loop that means position exceeds length of string so
return NULL */
}
int charPosition(char* str, char c)
{
int i=0;
while(str[i]!='\0') /* traverse string until '\0' is found */
{
if(str[i] == c) /*if character at position i is equal to character to be found then return position*/
return i;
i++;
}
return -1; /* if control comes out of loop that means character not found then return -1*/
}
complete program with driver code
#include <stdio.h>
char* substring(char* str, int iPos)
{
int i=0;
while(str[i]!='\0') /* string is terminated with '\0' in C. traverse string */
{
if(i == iPos) /* if index is same as position passed to function then return address of that charcter*/
return &str[i];
i++;
}
return (char*)NULL; /* if control comes out of the loop that means position exceeds length of string so
return NULL */
}
int charPosition(char* str, char c)
{
int i=0;
while(str[i]!='\0') /* traverse string until '\0' is found */
{
if(str[i] == c) /*if character at position i is equal to character to be found then return position*/
return i;
i++;
}
return -1; /* if control comes out of loop that means character not found then return -1*/
}
int main()
{
char str[] ="Hello World";
char *str1=substring(str,6);
if(str1 != NULL)
printf("\n%s",str1);
else
printf("\nposition is out of string length");
str1 = substring(str,45);
if(str1 != NULL)
printf("\n%s",str1);
else
printf("\nposition is out of string length");
int pos = charPosition(str,'l');
if(pos==-1)
{
printf("\ncharacter not found");
}
else
{
printf("\n Character found at position %d ",pos);
}
pos = charPosition(str,'z');
if(pos==-1)
{
printf("\ncharacter not found");
}
else
{
printf("\n Character found at position %d ",pos);
}
return 0;
}
output screenshot