Identyfying prefix in the same string as a suffix - c

Eg-
maabcma is valid because it contains ma as a proper prefix as well as a proper suffix.
panaba is not.
How do I find out if a word is valid or not as above in C language?
I'm not very good at string operations. So, please help me out with a pseudocode.
Thanks in advance.
I'm completely lost. T=number of test cases.
EDIT: New code. My best code so far-
#include<stdio.h>
#include<string.h>
void main()
{
int i,T,flag=0;
int j,k,len=0;
char W[10],X[10];
scanf("%d",&T);
for(i=0;i<T;i++)
{
scanf("%s",W);
for(len=0;W[len]!='\0';len++)
X[len]=W[len];
X[len]='\0';
for(j=len-1;j>=0;j--)
for(k=0;k<len;k++)
{
if(X[k]!=W[j])
flag=0;
else if((j-k)==(len-1))
flag==1;
}
if (flag == 1)
printf("NICE\n");
else
printf("NOT\n");
}
}
Still not getting the proper results. Where am I going wrong?

The thing is you are only setting the value of flag if a match exists, otherwise you must set it to 0. because see, if I have:
pammbap
my prefix is pam and suffix is bap.
According to the final for loop,
p and a match so flag is set to 1.
but when it comes to b and m it does not become zero. Hence, it returns true.

First, void is not a valid return type for main, unless you are developing for Plan 9.
Second, you should get into the habit of checking the return value of scanf() and all input functions in general. You can't rely on the value of T if the user does not input a number, because T is uninitialised. On that same note, you shouldn't use scanf with an unbounded %s scan operation. If the user enters 20 characters, this isn't going to fit into the ten character buffer that you have. An alternative approach is to use fgets to get a whole line of text at once, or, to use a bounded scan operation. If your array fits 10 characters (including the null terminator) then you can use scanf("%9s", W).
Third, single-character variable names are often very hard to understand. Instead of W, use word, instead of T, use testCount or something similar. This means that someone looking at your code for the first time can more easily work out what each variable is used for.
Most importantly, think about the process in your head, and maybe jot it down on paper. How would you solve this problem yourself? As an example, starting with n = 1,
Take the first n characters from the string.
Compare it to the last n characters from the string
Do they match?
If yes, print out the first n characters as the suffix and stop processing.
If no, increment n and try again. Try until n is in the middle of the string.
There are a few other things to think about as well, do you want the biggest match? For example, in the input string ababcdabab, the prefix ab is also the suffix, but the same can be said about abab. In this case, you don't want to stop processing, you want to keep going even if you find a prefix, so, you should just store the length of the largest prefix that is also the suffix.
Second-most-importantly, running into hurdles like this is incredibly common when learning C, so don't let this put a dampener on your enthusiasm, just keep trying!

Related

How can I fix the scanf to take data into the array?

Can someone please advise regarding the scanf?
"message" is an array of 4 rows by 16 columns.
After the user enters the numbers (all 1 digit integers), when hitting "Enter" there is an error message. As said - probably something with the scanf.
for (int i = 0; i < M; i++) {
for (int j = 0; j < columns; j++) {
scanf("%d", message[i][j]);
}
}
[Answer adapted from a now-deleted former question.]
scanf seems like a nice, simple, easy, convenient way to read input. And in some ways it is, but it turns out that using it correctly can be surprisingly difficult, and it's chock-full of pitfalls.
You're probably not going to want to learn about all of scanf's intricacies at first. So for now, here are some guidelines for using a subset of scanf's functionality, safely. (For reasons I fail to understand, everybody tells beginners to use scanf, but nobody ever teaches rules like these along with it.)
Remember to always use & in front of the variables you're trying to read. (This is a special rule, for scanf only. Don't try to use that & on the variables you pass to printf, for example.)
Exception to rule 1: Do not use the & when you are reading strings with %s.
If you are reading strings using %s, make sure the variable you read into is either a character array that's big enough for what the user is likely to type, or a pointer to malloc'ed memory that's big enough for what the user is likely to type. (See also note below about avoiding overflow.)
Be aware that %s reads strings that don't contain space characters. You can't use %s to read strings (like full names) that might contain spaces. (For now, please don't worry about how you might read a string that might contain spaces. See also rule 14.)
Don't try to use scanf and fgets together in the same program.
Don't try to use scanf and getchar together in the same program.
Try to limit yourself to only the format specifiers %d, %s, %f, and %lf, to read into variables of type int, string (see rule 3), float, and double, respectively.
If you want to read a character into a variable of type char, you can use " %c", but the mysterious extra explicit space character there is vital.
Use only one % sign in the format string, to read one variable. Don't try to read two or more variables in one scanf call.
Always check scanf's return value. If it returns 0, or the negative value EOF, that means it didn't successfully read anything. If it returns 1, that means it successfully read one value. (And if you break rule 9, and try to read multiple values, it'll return the number of values it did successfully read, anywhere between 0 and the number you asked for.)
If scanf returns 0 or EOF, indicating that the user did not type a valid value, just print an error message and exit. Don't try to write code that asks the user to try again, because the user's wrong input is still sitting on the input stream, and there's no good, simple way to get rid of it. (If you really want to write user-friendly code that re-prompts in case of error, scanf is not the right tool for the job.)
Never put whitespace after the format string. That includes the newline character \n. (That is, use "%d", not "%d " or "%d\n".)
Don't try to use the %[…] specifier.
If you break rule 13 (perhaps because someone told you that %[…] might be a way to read a string containing spaces, or a whole line), do not put an s after it. The format is %[…], not %[…]s.
These rules may seem restrictive, but if you follow these rules, you should be able to simply and easily and reliably get simple inputs into your simple programs, which is the goal here. scanf is otherwise remarkably hard to use, and experience has shown that there are something like 17 different horribly frustrating problems that tend to come up, and trying to solve them is a completely unnecessary distraction from your goal of learning C by writing simple C programs.
When you're reading strings with %s or %[…], there's a danger: no matter how big the array or malloc'ed buffer you're reading into is, the user might type more than that. To avoid overflow, you can use a format like %19s to explicitly tell scanf how many characters it's allowed to read. (And remember to subtract 1, to leave room for the terminating '\0'. That is, you'd use %19s to read into char str[20]; or char *p = malloc(20);.)
These rules are somewhat numerous. For a simpler set of rules, see this answer. Putting rules 7, 8, 9, 12, and 13 together, there are really only five complete format strings you want to use with scanf: "%d", "%s", "%f", "%lf", or " %c". (But no commas, no fixed strings, no whitespace other than the explicit space in " %c", nothing else.) Exception: as mentioned above, it's fine to use something like %19s to limit the length of a string being read.
If you need to do something more complicated, that you can't do while staying within these rules, it's time to either:
Learn enough about how scanf really works (and doesn't work) so that you can try to do the thing you want, but without getting stuck on one of those 17 problems, or
Learn how to do input using better and more powerful methods than scanf, perhaps by reading whole lines using fgets and then parsing them.
You're missing a "&" before "message[i][j]".
for (int i = 0; i < M; i++) {
for (int j = 0; j < columns; j++) {
scanf("%d", &message[i][j]);
}
}

How do I check if a string is a palindrome using recursion, without reversing or using a duplicate array

The conditions are:(these are part of the question, so I cannot bypass them)
I cannot reverse the array, so the strrev function, or writing a reverse function is pointless.
I cannot use another array, to copy the alphabets into it
There are whitespaces and commas, etc in the string and I have to disregard those while checking, but I am not allowed to remove those from the string
Literally the approach I had in my mind melted away after reading this,
and yes I HAVE to use recursion for this.
I just thought writing a function:
int palindrome(char arr[], int length) that returns a flag=0/1
should do the trick but I'm having trouble figuring out how to check beginning and end characters without removing the whitespace or commas.
Any ideas or hints towards a possible solution to this madness?
it should work for stuff like:
noon.
Sit on a potato pan, Otis
int palindrome(char arr[], int length);
With this signature, you can throw away characters from the beginning and end of the string, without changing the string itself:
To throw away the first character, increase the pointer:
palindrome(arr + 1, length - 1);
To throw away the last character, decrease the length:
palindrome(arr, length - 1);
Now think about a recursive definition of a palindrome; something like this:
If the first or last character is not a letter, throw it away and check whether the rest is a palindrome
If the first and last character are letters, compare them
Equal? Throw them away and check whether the substring is a palindrome
Not equal? Not a palindrome
You have to implement the logic carefully; this is only a general idea.

Why does this example use null padding in string comparisons? “Programming Pearls”: Strings of Pearls

In "Programming Pearls": Strings of Pearls, section 15.3 (Generating Text), the author introduces how to generate random text from an input document. In the source code, there are some things that I don't understand.
for (i = 0; i < k; i++)
word[nword][i] = 0;
The author explains: "After reading the input, we append k null characters(so the comparison function doesn't run off the end)." This explanation really confuses me, since it still works well after commenting these two lines. Why is this necessary?
Doing that reduces the number of weird cases you have to deal with when doing character-by-character comparisons.
alphabet
alpha___
If you stepped through this one letter at a time, and the null padding at the end of alpha wasn't there, you'd try to examine the next element... and run right off the end of the array.
The null padding basically ensures that when there's a character in one word, there's a corresponding character in the other. And since the null character has a value of 0, the shorter word always going to be considered as 'less than' the longer one!
As to why it seems to work without those lines, there's two associated reasons I can think of:
This was written in C. C does not guard its array boundaries; you can read whatever junk data is beyond the space that was allocated for it, and you'd never hear a thing.
Your input document is made such that you never compare two strings where one is a prefix of the other (like alpha is to alphabet).
As already explained in another answer, the purpose is to null terminate the string.
But I read the posted link and that loop doesn't make sense. If one looks at the comparison function used, there is no reason why the whole string must be filled with zeroes in this case. A plain word[nword][0] = 0; without the for loop would have worked just as fine. Or preferably:
word[nword][0] = '\0';
Filling the whole string with zeroes will add quite some overhead execution time.

C: Ways to use scanf

Can I use scanf(...) as argument to a function ?
Like this:
printInteger(scanf(....));
Can I use scanf to attribute the value that I read to some variable ?
Like this:
n = scanf(...);
p.s.: Here I'm explaining why I'm asking this.
This question can be a little weird I know, but I'm working in a project, which is developing a compiler that takes some language as input and then compile to C.
For example, this is my language, let's call 'stackoverflow' ;)
proc printInteger(integer k)
integer i;
begin
for i = 1 to k do
print i;
end
proc main()
integer n, i;
boolean ok;
begin
printInteger(getInteger);
n = getInteger;
ok = true;
while i < n do
begin
print i;
i = i + 1;
end
if ok then print 1; else print 0;
end
I won't get deeper in the language, but notice that getInteger means that I would like to do a scanf(...), what I mean is, when appears getInteger I would like to compile as scanf(...), so that's why I would like to know some ways to use scanf(...).
Can I use scanf(...) as argument to a function ? Like this:
printInteger(scanf(....));
Can I use scanf to attribute the value that I read to some variable ? Like this:
n = scanf(...);
You can use scanf as an argument to a function, but the real answer to both questions is no: scanf doesn't return any data scanned, it returns the number of items successfully scanned - or EOF if the end-of-input is reached before any successful scanning. You only get access to the items scanned using the pointers that you pass as scanf arguments to receive the values. So while you can pass scanf as an argument to a function, it won't do what you seem to want.
If you want to implement the getInteger operation in your language, in C, it's hard to make suggestions since only you know how this language/operation should work. Just using scanf, the implementation would look something like this:
int nextInt;
int numScanned = scanf("%d", &nextInt);
if (numScanned < 1)
handleError();
return nextInt;
But if you're doing general parsing for your language, then using scanf is a bad idea: you'll soon run into problems with the limitations of scanf, and you're not going to be able to anticipate all of the input types unless your language is really simple, simpler than the example that you've included.
To do this properly, find a good lex library for C. This will prevent a lot of headaches. Otherwise, if you must do the lexing yourself, start looking over fgets, get a line at a time from your input, and do the tokenizing yourself.
You ask:
Can I use scanf(...) as an argument to a function like this?
printInteger(scanf(....));
The answer to the first question is "Yes, but ...".
Can I use scanf to attribute the value that I read to some variable like this?
n = scanf(...);
The answer to the second is "No, because ...".
The "but" is mostly 'but it does not do what you expect so you would very seldom, if ever, do so'.
In the first example, scanf() returns either the (integer) number of successful conversions, or EOF if it reached EOF. In no case does it return the value that it just read (not least because, in general, it reads multiple values and most of them are not integers). So, if you want to print the number of values that was converted, you could use the printInteger() function to do so, but it is not what you'd normally want to do.
Similarly, in the second case, you can certainly assign the result of scanf() to an integer n as shown (and it is often sensible to do so if you're going to need to report an error). However, that is not the value that was read (assuming you had a %d conversion specification); it is the number of successful conversions.

Please Explain this Example C Code

This code comes from K&R. I have read it several times, but it still seems to escape my grasp.
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return(bufp>0)?buf[--bufp]:getchar();
}
int ungetch(int c)
{
if(bufp>=BUFSIZE)
printf("too many characters");
else buf[bufp++]=c;
}
The purpose of these two functions, so K&R says, is to prevent a program from reading too much input. i.e. without this code a function might not be able to determine it has read enough data without first reading too much. But I don't understand how it works.
For example, consider getch().
As far as I can see this is the steps it takes:
check if bufp is greater than 0.
if so then return the char value of buf[--bufp].
else return getchar().
I would like to ask a more specific question, but I literally dont know how this code achieves what it is intended to achieve, so my question is: What is (a) the purpose and (b) the reasoning of this code?
Thanks in advance.
NOTE: For any K&R fans, this code can be found on page 79 (depending on your edition, I suppose)
(a) The purpose of this code is to be able to read a character and then "un-read" it if it turns out you accidentally read a character too many (with a max. of 100 characters to be "un-read"). This is useful in parsers with lookahead.
(b) getch reads from buf if it has contents, indicated by bufp>0. If buf is empty, it calls getchar. Note that it uses buf as a stack: it reads it from right-to-left.
ungetch pushes a character onto the stack buf after doing a check to see if the stack isn't full.
The code is not really for "reading too much input", instead is it so you can put back characters already read.
For example, you read one character with getch, see if it is a letter, put it back with ungetch and read all letters in a loop. This is a way of predicting what the next character will be.
This block of code is intended for use by programs that make decisions based on what they read from the stream. Sometimes such programs need to look at a few character from the stream without actually consuming the input. For example, if your input looks like abcde12xy789 and you must split it into abcde, 12, xy, 789 (i.e. separate groups of consecutive letters from groups of consecutive digits) you do not know that you have reached the end of a group of letters until you see a digit. However, you do not want to consume that digit at the time you see it: all you need is to know that the group of letters is ending; you need a way to "put back" that digit. An ungetch comes in handy in this situation: once you see a digit after a group of letters, you put the digit back by calling ungetch. Your next iteration will pick that digit back up through the same getch mechanism, sparing you the need to preserve the character that you read but did not consume.
1. The other idea also shown here can be also called as a very primitive I/O stack mangement system and gives the implementation of the function getch() and ungetch().
2. To go a step further , suppose you want to design an Operating System , how can you handle the memory which stores all the keystrokes?
This is solved by the above code snippet.An extension of this concept is used in file handling , especially in editing files .In that case instead of using getchar() which is used to take input from Standard input , a file is used as a source of input.
I have a problem with code given in question. Using buffer (in form of stack) in this code is not correct as when getting more than one extra inputs and pushing into stack will have undesired effect in latter processing (getting input from buffer).
This is because when latter processing (getting input) going on ,this buffer (stack) will give extra input in reverse order (means last extra input given first).
Because of LIFO (Last in first out ) property of stack , the buffer in this code must be quene as it will work better in case of more than one extra input.
This mistake in code confused me and finally this buffer must be quene as shown below.
#define BUFSIZE 100
char buf[BUFSIZE];
int bufr = 0;
int buff = 0;
int getch(void)
{
if (bufr ==BUFSIZE)
bufr=0;
return(bufr>=0)?buf[bufr++]:getchar();
}
int ungetch(int c)
{
if(buff>=BUFSIZE && bufr == 0)
printf("too many characters");
else if(buff ==BUFSIZE)
buff=0;
if(buff<=BUFSIZE)
buf[buff++]=c;
}

Resources