I had earlier written a program in java which takes in as input a string as an input and checks if it is valid or not. The rules for deciding are:
1) The string is recognizable if and only if it contains the words “pi”, “ka”,”chu” as its fragments, in any order repeated any number of times .
2) If it contains any other fragments( or subsequence), Then it is unrecognizable
I was able to do so in java a bit easily as java has better support for string functions. My code is (this works fine)
import java.util.Scanner;
public class RecognisingWords {
public static void main(String[] args) throws Exception
{
Scanner inp= new Scanner(System.in);
String str;
System.out.println("Enter the string to be tested:");
str=inp.nextLine();
while(str.length()>0)
{
if(str.startsWith("pi"))
{
str= str.substring(2);
}
else if(str.startsWith("ka"))
{
str= str.substring(2);
}
else if(str.startsWith("chu"))
{
str= str.substring(3);
}
else
{
System.out.println("Unrecognisable Sequence");
break;
}
}
if(str.length()==0)
{
System.out.println("Recognisable Sequence");
}
}
}
However when i am writing the corresponding program in c (using pointers), my code runs into infinite loop. Please check my code and point wher the error is. Also is it possible to implement this program without using pointer ??
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
char str[10];
int len=0,flag=1;
char *ptr;
printf("Enter the string : ");
gets(str);
len=strlen(str);
ptr=str;
while(*ptr!='\0')
{
if(!strcmp("pi",ptr))
{
ptr=ptr+2;
}
else if(!strcmp("ka",ptr))
{
ptr=ptr+2;
}
else if(!strcmp("chu",ptr))
{
ptr=ptr+3;
}
else
{
printf("String not recognised");
flag=0;
break;
}
}
if(flag==1)
printf("String is recognised");
return 0;
}
I have corrected some of my very silly mistakes. Hope You people don’t mind
You probably want to advance your pointer by
ptr += 2orptr += 3rather than changing the character pointed by the pointer:*ptr = ....The logic in the loop is also not correct. You should loop until the current position of the pointer points to 0 (NUL character – which is the string terminator in C), by
while (*ptr != '\0'). You seem to have missed out thebreakin the lastelseblock.There is also the problem with
gets(str), which may cause buffer overflow problem in C. Security stuffs aside, your program will behave unexpectedly if you enter a string longer than 9 characters.There are potentially other problems with your C code that I cannot list out by just eyeballing your code.
EDIT
Another problem is that you used
strcmp, which will compare everything pointed to by the pointer with the fragment. i.e. If the input is “pikachu”, it will compare “pi” with “pikachu” and finds that “pi” is lexically smaller than “pikachu” and it will show that the string is not recognized. You probably wantstrncmp, in which you can specify the number of characters to compare.