Finding the needle in the Haystack using C - c

I'm having troubling figuring out why not my code is not iterating through the if statement until it finds the correct character.
#include <stddef.h>
#include <stdio.h>
char * my_strstr(char * param_1, char * param_2) {
int i;
int j;
for (i = 0; param_1[i] != '\0'; i++) {
printf("this is a loop for j %c\n", param_1[i]);
for (j = 0; param_2[j] != '\0'; j++) {
printf("this is a loop for j %c\n", param_2[j]);
if (param_1[i] == param_2[j]) {
printf("figuring out this %c\n", param_1[i]);
j++;
i++;
return &param_1[i];
printf("figuring out this %c\n", param_1[i]);
}
}
}
}
int main() {
char * param_1 = "hello";
char * param_2 = "ello";
printf("This is the string %s \n", my_strstr(param_1, param_2));
return 0;
}

I've pasted your code below with some edits and comments I hope will help.
#include <stddef.h>
#include <stdio.h>
char * my_strstr(char * param_1, char * param_2) {
int i;
int j;
for (i = 0; param_1[i] != '\0'; i++) {
// this should say "loop for i" shouldn't it?
printf("this is a loop for j %c\n", param_1[i]);
// use a flag to determine if you have found a match or not
int found = 1;
for (j = 0; param_2[j] != '\0'; j++) {
/* you actually want to compare param_1[i + j] == param_2[j] here
(respecting bounds of course). */
if (! param_1[i + j] || param_1[i + j] != param_2[j]) {
found = 0;
break;
}
printf("this is a loop for j %c\n", param_2[j]);
/* i don't understand what the following code was meant to do but you will
rarely want to increment i and j outside of the for ()
if (param_1[i] == param_2[j]) {
printf("figuring out this %c\n", param_1[i]);
j++;
i++;
return &param_1[i];
printf("figuring out this %c\n", param_1[i]);
}
*/
}
// here you want to check if you found it, and return if so.
if (found) {
return &param_1[i];
}
}
// need a default for if it is never found:
return NULL;
}
int main() {
char * param_1 = "hello";
char * param_2 = "ello";
printf("This is the string %s \n", my_strstr(param_1, param_2));
return 0;
}

Related

Allocated Dynamically Array of pointers

i'm really stuck.
I pust a big part of code you can try to run it on in online c compiler. My problem is weird, every time after 2 iteration i lost the data on spliter[0][0] when i mean "lost" is modified, for better understand please look what is printing it.
Inside
Inside the loop that iterates I wanted to see if the characters were well allocated in the present time and this is the case, only afterwards when I want to check it is impossible for me to do anything.
My program boils down to separating one character string according to another and dynamically allocating these character strings in my split. Each separator character counts as separator.
I have already prepared the test in comment. I really need help, too long time im stuck here..
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int is_c(char c, char *cha) {
while (*cha) {
if (*cha == c) {
return (1);
}
cha++;
}
return (0);
}
int ct_str(char *str, char *cha) {
int sw;
int nbr;
char item;
nbr = 0;
while (*str) {
if (!(is_c(*str, cha)) && *str >= 33 && *str <= 127 && sw == 1) {
sw = 0;
nbr+=1;
}
str++;
while (is_c(*str, cha)) {
str++;
sw = 1;
}
}
return (nbr);
}
int no_blk(char *str, int position, char *cha) {
while (!is_c(str[position], cha)) {
if (str[position] >= 33 && str[position] <= 127)
return (1);
position++;
}
return (0);
}
int get_size(char *str, int position, char *cha) {
int item;
item = position;
int j;
j = 0;
while (str[item]) {
if (is_c(str[item], cha))
return (j);
item++;
j++;
}
return (0);
}
void split_this(char **split, char *str, char *cha) {
int i;
int level;
int sw;
int e;
level = 0;
i = 0;
int item = 0;
int element = 0;
while(str[i + 1]) {
e = 0;
while(is_c(str[i], cha)) {
sw = 1;
i++;
}
if(sw == 1 && (!is_c(str[i], cha)) && no_blk(str, i, cha)) {
split[level] = (char*)malloc(sizeof(char) * get_size(str, i, cha) + 1);
e = i;
//printf("%i \n", get_size(str, i, cha));
while(e - i < get_size(str, i, cha)) {
split[level][e - i] = str[e];
//printf("%c", split[level][e - i]);
split[level][(e + 1) - i] = '\0';
e++;
}
printf("%c", split[0][0]);
sw = 0;
level++;
}
i++;
}
free(split);
/*
int it = 0;
int ee;
while(split[it]) {
ee = 0;
while(split[it][ee]) {
printf("%c", split[it][ee]);
ee++;
}
it++;
}
*/
}
void ft_split(char *str, char *cha) {
char **spliter = NULL;
spliter = (char**)malloc(sizeof(char) * ct_str(str, cha) + 1);
split_this(spliter, str, cha);
}
int main(int argc, char **argv) {
//if (argc == 3)
//ft_split(argv[1], argv[2]);
ft_split("%%am%s%s%ss%%s%%%qsdqsd%%%on%vs%lre%" , "%%");
return (0);
}

how to reverse order of words in string using C?

I am trying to reverse the order of words in a string, but my output is a bunch of junk that makes no sense. I don't know what is the problem, maybe the loops are broken.
Appreciate it if someone can explain what is wrong with my code below. I still new to C programming and this kind of problem is kind of frustrating.
#include<stdio.h>
int main()
{
//declare variable
char string[100], rev_string[100];
//declare number of loop
int i, j, len;
printf("enter the string: ");
scanf("%s",string);
//finding the length
len = strlen(string);
printf("strings length: %d\n", len);
for (i = len - 1; i >= 0; i--)
for (j = 0; j < len - 1; j++)
rev_string[j] = string[i];
rev_string[j] = '\0';
if (strcmp(string, rev_string) == 0)
printf("rev_string: %s is a palindrome", rev_string);
else
printf("rev_string : %s is not a palindrome words",rev_string);
return(0);
}
Your title is a bit confusing because your code seems to be a palindrome check and it should reverse the string, not the order of the words.
To reverse the string you can simply do:
for (i = 0; i < len; i++)
rev_string[i] = string[len - i - 1];
This code can help you :
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define NCHARS 256 /* constant to count array size, covers ASCII + extended ASCII */
int ispalindrom (const char *s1, const char *s2)
{
int count[NCHARS] = {0}; /* counting array, covers all extended ASCII */
for (; *s1; s1++) /* loop over chars in string 1 */
if (!isspace(*s1)) /* if not whitespace */
count[(int)*s1]++; /* add 1 to index corresponding to char */
for (; *s2; s2++) /* loop over chars in string 2 */
if (!isspace(*s2)) /* if not whitespace */
count[(int)*s2]--; /* subtract 1 from index corresponding to char */
for (int i = 0; i < NCHARS; i++) /* loop over counting array */
if (count[i]) /* if any index non-zero, not anagram */
return 0;
return 1; /* all chars used same number of times -> anagram */
}
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
char str2[100];
printf("enter the string :");
scanf("%[^\n]s", str);
for (int i = 0;str[i] != '\0'; i++)
{
str2[i]=str[i];
}
/* reads into 2d character array */
for (int i = 0;str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
str1[k][j]='\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
j++;
}
}
str1[k][j] = '\0';
/* reverses each word of a given string */
for (int i = 0;i <= k;i++)
{
len = strlen(str1[i]);
for (int j = 0, x = len - 1;j < x;j++,x--)
{
temp = str1[i][j];
str1[i][j] = str1[i][x];
str1[i][x] = temp;
}
}
for (int i = 0;i <= k;i++)
{
printf("%s ", str1[i]);
}
printf("\n\n");
if (ispalindrom(str1, str2)==0)
{
printf("The word is Palindrom !\n");
}
else
{
printf("The word is not Palindrom !\n");
}
}
#include <stdbool.h>
#include <stdio.h>
bool ispalindrom(char *str,int k)
{
for(int i=0;i<k;i++)
{
if(str[i]!=str[k-i-1])
{
return false;
}
}
return true;
}
int main()
{
char string[100];
printf("enter the string: ");
scanf("%s",string);
if (ispalindrom(string,strlen(string)))
{
printf("\nrev_string: %s is a palindrome\n", string);
}
else
{
printf("\nrev_string : %s is not a palindrome words\n",string);
}
}
you can use a loop first to reverse the string first and then use strcomp()
#include<stdio.h>
#include <string.h>
int main()
{
//declare variable
char string[100], rev_string[100];
//declare number of loop
int i, j =0 , len;
printf("enter the string: ");
scanf("%s",string);
//finding the length
len = strlen(string);
printf("strings length: %d\n", len);
for (i = len - 1;i >= 0;i--){
rev_string[j] = string[i];
j++;
}
//check the rev_string if you want
/*for (i = 0; i < len; i++){
printf("%c\n",rev_string[i]);
}*/
if(strcmp(rev_string,string) == 0){
printf("Is Palindrome\n");
return(0);
}else{
printf("Is not Palindrome\n");
return(1);
}
}

String array prints out trash values

So I have an assignment where I should delete a character if it has duplicates in a string. Right now it does that but also prints out trash values at the end. Im not sure why it does that, so any help would be nice.
Also im not sure how I should print out the length of the new string.
This is my main.c file:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main() {
char string[256];
int length;
printf("Enter char array size of string(counting with backslash 0): \n");
/*
Example: The word aabc will get a size of 5.
a = 0
a = 1
b = 2
c = 3
/0 = 4
Total 5 slots to allocate */
scanf("%d", &length);
printf("Enter string you wish to remove duplicates from: \n");
for (int i = 0; i < length; i++)
{
scanf("%c", &string[i]);
}
deleteDuplicates(string, length);
//String output after removing duplicates. Prints out trash values!
for (int i = 0; i < length; i++) {
printf("%c", string[i]);
}
//Length of new string. The length is also wrong!
printf("\tLength: %d\n", length);
printf("\n\n");
getchar();
return 0;
}
The output from the printf("%c", string[i]); prints out trash values at the end of the string which is not correct.
The deleteDuplicates function looks like this in the functions.c file:
void deleteDuplicates(char string[], int length)
{
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length;)
{
if (string[j] == string[i])
{
for (int k = j; k < length; k++)
{
string[k] = string[k + 1];
}
length--;
}
else
{
j++;
}
}
}
}
There is a more efficent and secure way to do the exercise:
#include <stdio.h>
#include <string.h>
void deleteDuplicates(char string[], int *length)
{
int p = 1; //current
int f = 0; //flag found
for (int i = 1; i < *length; i++)
{
f = 0;
for (int j = 0; j < i; j++)
{
if (string[j] == string[i])
{
f = 1;
break;
}
}
if (!f)
string[p++] = string[i];
}
string[p] = '\0';
*length = p;
}
int main() {
char aux[100] = "asdñkzzcvjhasdkljjh";
int l = strlen(aux);
deleteDuplicates(aux, &l);
printf("result: %s -> %d", aux, l);
}
You can see the results here:
http://codepad.org/wECjIonL
Or even a more refined way can be found here:
http://codepad.org/BXksElIG
Functions in C are pass by value by default, not pass by reference. So your deleteDuplicates function is not modifying the length in your main function. If you modify your function to pass by reference, your length will be modified.
Here's an example using your code.
The function call would be:
deleteDuplicates(string, &length);
The function would be:
void deleteDuplicates(char string[], int *length)
{
for (int i = 0; i < *length; i++)
{
for (int j = i + 1; j < *length;)
{
if (string[j] == string[i])
{
for (int k = j; k < *length; k++)
{
string[k] = string[k + 1];
}
*length--;
}
else
{
j++;
}
}
}
}
You can achieve an O(n) solution by hashing the characters in an array.
However, the other answers posted will help you solve your current problem in your code. I decided to show you a more efficient way to do this.
You can create a hash array like this:
int hashing[256] = {0};
Which sets all the values to be 0 in the array. Then you can check if the slot has a 0, which means that the character has not been visited. Everytime 0 is found, add the character to the string, and mark that slot as 1. This guarantees that no duplicate characters can be added, as they are only added if a 0 is found.
This is a common algorithm that is used everywhere, and it will help make your code more efficient.
Also it is better to use fgets for reading input from user, instead of scanf().
Here is some modified code I wrote a while ago which shows this idea of hashing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUMCHAR 256
char *remove_dups(char *string);
int main(void) {
char string[NUMCHAR], temp;
char *result;
size_t len, i;
int ch;
printf("Enter char array size of string(counting with backslash 0): \n");
if (scanf("%zu", &len) != 1) {
printf("invalid length entered\n");
exit(EXIT_FAILURE);
}
ch = getchar();
while (ch != '\n' && ch != EOF);
if (len >= NUMCHAR) {
printf("Length specified is longer than buffer size of %d\n", NUMCHAR);
exit(EXIT_FAILURE);
}
printf("Enter string you wish to remove duplicates from: \n");
for (i = 0; i < len; i++) {
if (scanf("%c", &temp) != 1) {
printf("invalid character entered\n");
exit(EXIT_FAILURE);
}
if (isspace(temp)) {
break;
}
string[i] = temp;
}
string[i] = '\0';
printf("Original string: %s Length: %zu\n", string, strlen(string));
result = remove_dups(string);
printf("Duplicates removed: %s Length: %zu\n", result, strlen(result));
return 0;
}
char *remove_dups(char *str) {
int hash[NUMCHAR] = {0};
size_t count = 0, i;
char temp;
for (i = 0; str[i]; i++) {
temp = str[i];
if (hash[(unsigned char)temp] == 0) {
hash[(unsigned char)temp] = 1;
str[count++] = str[i];
}
}
str[count] = '\0';
return str;
}
Example input:
Enter char array size of string(counting with backslash 0):
20
Enter string you wish to remove duplicates from:
hellotherefriend
Output:
Original string: hellotherefriend Length: 16
Duplicates removed: helotrfind Length: 10

Palindrome finder in C?

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.

Trying to compare two strings

It is sufficient to say that I am new to C so please have show some mercy ;).
I'm trying to compare two strings. The output shouldn't contain common characters. Sadly it does.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char msg[15] = "blueberry";
int c;
int s[15];
int j = 0;
int i = 0;
int k= 0;
int ok = 0;
int t = 0;
while (i < 15 && (c = getchar()) != '\n')
{
s[i] = c;
++i;
}
for (t=j=0; t < 15; ++t)
{
ok = 1;
//printf ("%c", s[t]);
}
for (k=0; msg[k] != '\0'; ++k)
{
if (s[t] == msg[k])
{
ok = 0;
}
}
if (ok == 1)
{
s[j] = s[t];
j++;
}
s[j] = '\0';
for (j = 0; j < 15; ++j)
printf ("%c ", s[j]);
}
The input from the keyboard is blackberry, expected output should've been U but sadly it is not. Any help please. Also why is it entering the nested for loop irrespective of condition?
My big thanks to everyone, it helped me a lot. I've figured out a way & am ok with the output. I've borrowed some ideas from A4L :).
To compare two string, you can use strcmp().
The following is a string compare program that you can use for your reference. I has both array and pointer version for better understanding.
#include <stdio.h>
int strcmp1(char a[], char b[])
{
int i=0;
while (a[i] == b[i]) {
if (a[i] == '\0')
return 0;
i++;
}
return a[i]-b[i];
}
int strcmp2(char *a, char *b)
{
while (*a == *b) {
if (*a == '\0')
return 0;
a++; b++;
}
return *a-*b;
}
int main()
{
char s1[] = "test string1";
char s2[] = "test string";
char s3[] = "aaa";
char s4[] = "bbb";
printf("strcmp1(%s, %s) = %d \n", s1, s2, strcmp1(s1, s2));
printf("strcmp2(%s, %s) = %d \n", s3, s4, strcmp2(s3, s4));
return 0;
}
given that msg contains "blueberry" and s contains "blackberry" this should do it
for (int i=0; i < strlen(msg); i++) {
for (int j = 0; j < strlen(s); j++) {
if (msg[i] != s[j]) {
printf ("%c", msg[i]);
}
}
}
yes it's ugly (using the strlen in the for gives me the chills, but I'm still low on coffeine today ^^)
i guess you want to find the first letter where the input differs from message
here is your own code with some fixes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char msg[15] = "blueberry";
int c;
char s[15];
int i = 0;
int k= 0;
int ok = 0;
while (i < 15 && (c = getchar()) != '\n')
{
s[i] = (char) c;
++i;
}
// make sure to terminate the string after hitting enter
s[i] = '\0';
printf("input: %s\n", s);
printf("messg: %s\n", msg);
// run through both input and message with one counter
for (k=0; ok == 0 && msg[k] != '\0' && s[k] != '\0'; )
{
// if different chars stop
if (s[k] != msg[k]){
ok = 1;
} else {
// next char
k++;
}
}
if (ok == 1)
{
printf ("diff # index %d -> %c\n", k, msg[k]);
}
else
{
printf ("no diff\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
//Length to match
int comm(char* s1, char* s2){
int len = 0;
while(*s1 && *s2 && *s1++ == *s2++)
++len;
return len;
}
//commdiffcomm
/*
int commr(char* s1, char* s2){
int len = 0, limit;
int len1,len2;
len1 = strlen(s1);
len2 = strlen(s2);
limit = len1 > len2 ? len2 : len1;
s1 = s1 + len1;
s2 = s2 + len2;
while(limit-- && *--s1 == *--s2)
++len;
return len;
}
//bad
int diff(char* s1, char* s2, int* len1, int* len2){
int len, lenr, s1_len, s2_len, wk_max, i, j;
len = comm(s1, s2);
if(strcmp(s1, s2)==0){
*len1 = *len2 = 0;
return len;
}
lenr = commr(s1, s2);
*len1 = strlen(s1) - len - lenr;
*len2 = strlen(s2) - len - lenr;
return len;
}
*/
int diff(char* s1, char* s2, int* len1, int* len2){
int len, s1_len, s2_len, wk_max, i, j;
len = comm(s1, s2);
if(strcmp(s1, s2)==0){
*len1 = *len2 = 0;
return len;
}
s1_len = strlen(s1 + len + 1);
s2_len = strlen(s2 + len);
wk_max = 0;
for(i = 1; i < s1_len ; i++){
for(j = 0; j < s2_len; j++){
int com_len;
com_len = comm(s1 + len + i, s2 + len + j);
if(wk_max < com_len){
wk_max = com_len;
*len1 = i;
*len2 = j;
}
}
}
return len;
}
int main(){
char str1[16] = "blueberry";
char str2[16] = "blackberry";
char dif1[16] = "";
char dif2[16] = "";
int len0;//length of top to diff pos
int len1;
int len2;
len0 = diff(str1, str2, &len1, &len2);
strncpy(dif1, str1 + len0, len1);
strncpy(dif2, str2 + len0, len2);
if(len1 !=0 && len2 != 0){
printf("%s different %s at position %d length %d (\"%s\")\n", str1, str2, len0, len1, dif1);
printf("%s different %s at position %d length %d (\"%s\")\n", str2, str1, len0, len2, dif2);
} else {
printf("two string is same.");
}
return 0;
}
/*
blueberry different blackberry at position 2 length 2 ("ue")
blackberry different blueberry at position 2 length 3 ("ack")
*/
There are a few problems with the code as is:
You don't null-terminate your input string. Attempting to use it with c string functons would spell trouble. To fix that, change
while (i < 15 && (c = getchar()) != '\n')
{
s[i] = c;
++i;
}
to
while (i < 14 && (c = getchar()) != '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
Your specification is unclear as to whether you want your program to print the letters unique to msg, or to both s and msg. (i.e, do you want msg-s or (msg ∪ s)-(msg ∩ s) Assuming the first, the important part of your program goes like this:
k=0;
for(i=0;i<strlen(msg);i++){
int exists = 0;
for(j=0;!exists && j<strlen(s);j++){
if(msg[j] == s[i])
exists = 1;
}
if(!exists)
msg[k++] = msg[i];
}
s[k] = '\0';
The inner loop checks if s contains the current character in msg. If it does, we don't do anything, but if it doesn't, we append it to the end of a sublist we're creating on top of the bits of msg we've already processed.
your code is a mess even after the rewrite - there are too many errors to describe in detail
/*
blackbery
b l u e b e r r y
. . a c k b e . .
result = non-equal
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char msg[15] = "blueberry";
int c, s[15], i,j,k, ok;
for (i=0; i < 15; i++) s[i] = 0;
for (i=0; i < 15 && (c = getchar()) != '\n'; i++) s[i] = c;
for (ok=1, k=0; msg[k] != '\0'; ++k)
if (s[k] != msg[k]) ok = 0; else s[k] = '.';
for (j = 0; j < 15; ++j) printf ("%c ", msg[j]);
printf("\n");
for (j = 0; j < 15; ++j) printf ("%c ", s[j]);
printf("\nresult = %s\n", ok ? "equal" : "non-equal");
}

Resources