I used following code..but i am looking for proper condition to put. please help me out with it.
int main(){
int k = 0;
char a[9] = {'\0'}, b[9] = {'\0'};
printf("enter string \n");
gets(a);
int p = strlen(a);
for(int i = p-1; i >= 0; i--){
b[k] = a[i];
k = k+1;
}
for(int j = 0; j < p; j++){
if(a[j] == b[j]){
continue;
}else
printf("not pal");
break;
}
return 0;
}
for(int j=0;j<p;j++)
{
if(a[j]!=b[j])
{
printf("not pal");
return 0;
}
}
printf("string is Palindrome");
return 0;
here is code..
int main(){
int k=0, flag;
char a[9]={'\0'},b[9]={'\0'};
printf("enter string \n");
gets(a);
int p = strlen(a);
for(int i=p-1;i>=0;i--){
b[k]=a[i];
k=k+1;
}
for(int j=0;j<p;j++){
if(a[j]==b[j]){
flag=0;
}else
flag=1;
break;
}
if(flag==0)
printf("yes");
else
printf("no");
return 0;
}
No need to copy the string. The code below uses the size of the whole string to copy the mirrored letter and checks for equality. Complexity is O(N/2) (if that even exists :-p.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
bool is_palindrome(const char* s)
{
const size_t len = strlen(s);
size_t i=0;
while(i<len/2-1)
{
if(s[i] != s[len-i-1])
return false;
++i;
}
return true;
}
int main()
{
const char* s1 = "palindrome";
const char* s2 = "palindromemordnilap";
if(is_palindrome(s1))
printf("uhoh");
if(is_palindrome(s2))
printf("yay!");
}
Live demo here.
Related
I am currently fighting with a primitive search routine. It uses strcmp to compare a string given against a two dim array of strings.
GDP returns:
"__strcmp_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S:30 30 ../sysdeps/x86_64/multiarch/strcmp-sse2-unaligned.S: No such file or directory".
Edited: Trying to move on, added command line for string input procedure. Somehow, it is mistaken.
here is my code
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char dictionary()
{
char **strings = (char**)malloc(5*sizeof(char*));
int i = 0;
for(i = 0; i < 5; i++){
//printf("%d\n", i);
strings[i] = (char*)malloc(7*sizeof(char));
}
sprintf(strings[0], "mark");
sprintf(strings[1], "ala");
sprintf(strings[2], "wojtek");
sprintf(strings[3], "tom");
sprintf(strings[4], "john");
for(i = 0; i < 5; i++){
printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
}
for(i = 0; i < 5; i++){
free(strings[i]);
}
free(strings);
}
int cmp(char *s1, char *s2[][10]){
int i = 0;
//size_t l = strlen(s1);
for (i = 0; i < 5; i++){
if (strcmp(s1, s2[i][7*sizeof(char)]) == 0)
{
printf("OK \n");
} else {
printf("sth is wrong \n");
}
return 0;
}
}
int main(){
char BufText[255];
int n=0;
char sign;
fflush(stdin);
n = 0;
do {
sign = getchar();
BufText[n ++] = sign;
if(n >= 253) break;
} while (sign !='\n');
BufText [n] = 0;
char **dict = dictionary();
cmp(BufText, dict);
free_dictionary(dict);
return 0;
}
As said in the comments, there's a lot of flaws in your code.
First in your main, you're trying to cmp("ala", dictionary); but dictionary is an undeclared variable. I think you wanted to use the result of your dictionary() call into the cmp call. So you need to store the dictionary() result into your dictionary variable. It can't actually be done because your dictionary() func does not return anything and free the allocated dict before it can be used.
I could continue this way but here's a patched version of your code. Feel free to ask for clarifications.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char **dictionary()
{
char **dict = (char**)malloc(sizeof(char*) * 5);
int i = 0;
for (i = 0; i < 5; i++)
dict[i] = (char*)malloc(sizeof(char) * 7);
sprintf(dict[0], "mark");
sprintf(dict[1], "ala");
sprintf(dict[2], "wojtek");
sprintf(dict[3], "tom");
sprintf(dict[4], "john");
for (i = 0; i < 5; i++)
printf("Line #%d(length: %lu): %s\n", i, strlen(dict[i]),dict[i]);
return (dict);
}
void free_dictionary(char **dict)
{
for (int i = 0; i < 5; i++)
free(dict[i]);
free(dict);
}
void cmp(char *s1, char *s2[5])
{
int i = 0;
for (i = 0; i < 5; i++)
{
if (strcmp(s1, s2[i]) == 0)
printf("OK \n");
else
printf("sth is wrong \n");
}
}
int main()
{
char **dict = dictionary();
cmp("ala", dict);
free_dictionary(dict);
return (0);
}
It is a program about user input text and pattern. And use a function to return the value of index of the pattern. If pattern cannot be found, return -1;For some reason I keep getting -1 for return value;
Here is my code:
#include<stdio.h>
#include<string.h>
int contains(const char *text,const char *pattern){
int lengthT,lengthP,i;
int j = 0;
for(i = 0; i < 10; i++){//get the length of pattern
if(pattern[i] == '\0'){
lengthP = i;
break;
}
}
for(i = 0;i < 100; i++){//get the length of text
if(text[i] == '\0'){
lengthT = i;
break;
}
}
for(i = 0;i < lengthT;i++){
if(text[i] == pattern[0]){
for(j = 1;j <= lengthP + 1;j++){
if(text[i+j] == pattern[j]){
if(j >= lengthP){
return i;
}
continue;
}
}
}
return -1;
}
}
int main(){
const char text[100];
const char pattern[10];
printf("Enter the text: ");
scanf("%s",&text);
printf("Enter the pattern: ");
scanf("%s",&pattern);
printf("Pattern %s occurs in %s at the location %d.\n",pattern,text,contains(text,pattern));
return 0;
}
You have placed the return -1; at wrong position. It should be placed outside the for loop iterating across the text otherwise the function will directly return -1 if the first letter of text and pattern are not same.
Also, after correcting return statement, I found out that your logic was somewhat wrong.Here is code that is correct according to me.
#include<stdio.h>
#include<string.h>
int contains(const char *text,const char *pattern){
int lengthT,lengthP,i;
int j = 0;
lengthP = strlen(pattern);
lengthT = strlen(text);
for(i = 0;i < lengthT;i++){
if(text[i] == pattern[0]){
printf(" f1");
for(j = 1;j <lengthP;j++){
if(text[i+j] == pattern[j]){
if(pattern[j+1]== '\0'){
return i;
}
continue;
}
}
}
}
return -1;
}
int main(){
const char text[100];
const char pattern[10];
printf("Enter the text: ");
scanf("%s",&text);
printf("Enter the pattern: ");
scanf("%s",&pattern);
printf("Pattern %s occurs in %s at the location %d.\n",pattern,text,contains(text,pattern));
return 0;
}
I'm trying to make a palindrome finder in C and I don't know where it is going wrong, no matter what I get the output false on the 2 different ways that I have tried to code this. I have only just started C (in the past week) so if you could explain things simply that'd be great, thanks!
//way1
#include <stdio.h>
int read_char() { return getchar(); }
void read_string(char* s, int size) { fgets(s, size, stdin); }
void print_char(int c) { putchar(c); }
void print_string(char* s) { printf("%s", s); }
int is_palin(char word[]) {
int m = 0;
int arr_len = sizeof(word) / sizeof(char); //change to char_index
int n = arr_len;
int t = 1;
if(n % 2 != 0) {
for (m=0; m < ((n-1)/2); m++) {
if(word[m] != word[n-m-2]) {
t = 0;
}
else {
t = 1;
}
}
}
else {
for (m=0; m < (n/2)-1; m++) {
if(word[m] != word[n-m-2]) {
t = 0;
}
else {
t = 1;
}
}
}
if(t == 1) {
return 1;
}
else {
return 0;
}
}
int main(void) {
char word[6] = "civic";
int arr_len = sizeof(word)/sizeof(char);
if (is_palin(word) == 1) {
printf("is palin\n");
}
else {
printf("is not palin\n");
}
printf(word);
printf("\n");
printf("%d\n", arr_len);
return 0;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//way2
#include <stdio.h>
int read_char() { return getchar(); }
void read_string(char* s, int size) { fgets(s, size, stdin); }
void print_char(int c) { putchar(c); }
void print_string(char* s) { printf("%s", s); }
int is_palin(char word[]) {
int m = 1;
int input_length = sizeof(word);
int j = input_length-1;
int i = 0;
for(i=0; i <= j; i++) {
if(word[i] != word[j]) {
m = 0;
j--;
}
}
if(m == 1) {
return 1;
}
else {
return 0;
}
}
int main(void) {
char word[6] = "civic";
int input_length = sizeof(word);
if (is_palin(word) == 1) {
printf("is palin\n");
}
else {
printf("is not palin\n");
}
printf(word);
printf("\n");
printf("%d\n", input_length);
return 0;
}
Please try this, it works fine.
#include <stdio.h>
int main( )
{
int flag = 0;
int length = 0;
int len2 = 0;
int i = 0;
char name[130];
char p[130];
char q[130];
printf( "please enter a name or sentence\n" );
scanf( "%[^\n]", name );
length = strlen( name );
len2 = length;
strcpy( p, name );
memset( q, '.', length ); // handy to debug comparaison
q[length] = '\0';
for ( i = 0; i < length; i++ )
{
q[--len2] = p[i];
}
printf( "\n p==%s", p );
printf( "\n q==%s", q );
getchar( );
if ( !strcmp( p, q ) )
flag = 1;
if ( flag == 1 )
printf( "\npalindrome\n" );
else
printf( "\nnot a palindrome\n" );
return 0;
}
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program to do this, see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.
C program for removal of duplicate characters from the given string. It uses the O(n2) can we do it in O(n) order. Please comment on this program.
int main()
{
char a[100],b[100],temp='\0';
int i,n,j,count=0,p=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
i=0;
while(i < n)
{
count=0;
temp = a[i];
for(j = i ; j < n ; j++ )
{
if(temp==a[j])
{
count++;
}
}
if(count<2)
{
b[k] = temp;
k++;
}
i++;
}
b[k]='\0';
printf("THE RESULTED STRING IS \n");
for(p = 0 ; p < k ; p++)
printf("%c ",b[p]);
printf("\n");
return 0;
}
You can create a O(n) algorithm for this.
Steps:
Create another array bucket[] with size 255. (Should adjust all the characters)
Initialise every element in bucket[] to 0.
Run a loop and increment the bucket[] at the index a[i].
Now, run another loop through the bucket[], if bucket[i] > 0, append the (char) i to the b[] array.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
int bucket[256] = {0};
int i;
printf("Enter the string:");
scanf("%s",a);
int n = strlen(a);
for(i = 0; i < n; ++i)
{
//Incrementing the character count of each character.
bucket[a[i]]++;
}
//Keep track of the index where the next character is to be appended.
int b_pos = 0;
for (i = 0; i < 256; ++i)
{
//Character occurs in a[], we don't care if it occurs once
//or twice, we just need one instance of it.
if (bucket[i] > 0)
{
b[b_pos] = (char) i;
b_pos++;
}
}
b[b_pos] = '\0';
printf("Modified string : %s",b);
}
Take a look at this:
int main()
{
char a[100],b[100];
int i,n,j,count=0,k=0;
printf("ENTRE THE STRING \n");
scanf("%s",a);
n = strlen(a);
b[0] = a[0];
k = 1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(a[i] == b[j])
{
count = 1;
break;
}
}
if(count == 0)
{
b[k] = a[i];
k++;
}
else
{
count = 0;
}
}
b[k] = 0;
printf("RESULT %s",b);
return 0;
}
I've nearly finished my anagram solver program where I input two strings and get the result of whether they are anagrams of each other. For this example i'm using 'Payment received' and 'Every cent paid me'.
The problem i'm getting is when I output the letterCount arrays, letterCount1 is incorrect (it doesn't think there is a character 'd' but there is.) but letterCount2 is correct.
Can anyone see a problem with this because i'm completely baffled?
#include <stdio.h>
#include <string.h>
int checkAnagram(char string1[], char string2[])
{
int i;
int count = 0, count2 = 0;
int letterCount1[26] = {0};
int letterCount2[26] = {0};
for(i = 0; i < strlen(string1); i++)
{
if(!isspace(string1[i]))
{
string1[i] = tolower(string1[i]);
count++;
}
}
for(i = 0; i < strlen(string2); i++)
{
if(!isspace(string2[i]))
{
string2[i] = tolower(string2[i]);
count2++;
}
}
if(count == count2)
{
for(i = 0; i < count; i++)
{
if(string1[i] >='a' && string1[i] <= 'z')
{
letterCount1[string1[i] - 'a'] ++;
}
if(string2[i] >='a' && string2[i] <= 'z')
{
letterCount2[string2[i] - 'a'] ++;
}
}
printf("%s\n", string1);
for(i = 0; i < 26; i++)
{
printf("%d ", letterCount1[i]);
printf("%d ", letterCount2[i]);
}
}
}
main()
{
char string1[100];
char string2[100];
gets(string1);
gets(string2);
if(checkAnagram(string1, string2) == 1)
{
printf("%s", "Yes");
} else
{
printf("%s", "No");
}
}
That's because your count holds the count of non-space characters, but you keep the strings with the spaces.
For example, the string "hello world" has 11 characters, but if you run it through the loops your count will be 10 (you don't count the space). However, when you later go over the strings and count the appearance of each letter, you will go over the first 10 characters, therefore completely ignoring the last character - a 'd'.
To fix it, you need to go over all characters of the string, and only count the alphanumeric ones.
I fixed it for you:
#include <stdio.h>
#include <string.h>
int checkAnagram(char string1[], char string2[])
{
int i;
int count = 0, count2 = 0;
int letterCount1[26] = {0};
int letterCount2[26] = {0};
int len1 = strlen(string1);
int len2 = strlen(string2);
for(i = 0; i < len1; i++)
{
if(!isspace(string1[i]))
{
string1[i] = tolower(string1[i]);
count++;
}
}
for(i = 0; i < len2; i++)
{
if(!isspace(string2[i]))
{
string2[i] = tolower(string2[i]);
count2++;
}
}
if(count == count2)
{
for (i=0; i<len1; i++)
if (!isspace(string1[i]))
letterCount1[string1[i]-'a']++;
for (i=0; i<len2; i++)
if (!isspace(string2[i]))
letterCount2[string2[i]-'a']++;
int flag = 1;
for(i = 0; flag && i < 26; i++)
if (letterCount1[i] != letterCount2[i])
flag = 0;
return flag;
}
return 0;
}
main()
{
char string1[100];
char string2[100];
gets(string1);
gets(string2);
if(checkAnagram(string1, string2) == 1)
{
printf("%s", "Yes");
} else
{
printf("%s", "No");
}
}
First, don't calculate an string's length inside a loop. I extracted them into len1 and len2 variables.
Second, your loop was wrong! You shouldn't go up to count, you should go up to that string's length.
Third, you didn't return anything from checkAnagram function.