Write program to find and replace the character in the word - c

Program question is:
Write a C program to find and replace the character in the word.
Here flag('A'/'F') indicates whether all occurrences has to be replaced or only the first occurrence has to be replaced.
I have written this code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void cond(char *a,int n,char k,char l,char m)
{
printf("The word is\n");
int i,count=0,max=0;
switch(m)
{
case 'A':
for(i=0;i<n;i++)
{
if(a[i]==k)
{
a[i]=l;
count++;
}
}
if(count==0)
{
printf("No such character present in the word.");
}
else
for(i=0;i<n;i++)
{
printf("%c",a[i]);
}
break;
case 'F':
for(i=0;i<n;i++)
{
while(max<1)
{
if(a[i]==k)
{
a[i]=l;
max++;
}
}
}
if(max==0)
{
printf("No such character present in the word.");
}
else
for(i=0;i<n;i++)
{
printf("%c",a[i]);
}
break;
}
}
int main()
{
char a[20],b,e,p;
printf("Enter the word:\n");
scanf("%s",a);
printf("Enter the character to be find:\n");
scanf("%c\n",&b);
printf("Enter the character to be replaced:\n");
scanf("%c\n",&e);
printf("Enter the 'A'/'F':\n");
scanf("%c\n",&p);
int n=strlen(a);
cond(a,n,b,e,p);
return 0;
}
It does not give any output
For example:
If I input this
Enter the word: aeroplane
Enter the character to be find:a
Enter the character to be replaced:z
Enter the 'A'/'F': A
The word is
It gives a blank output
someone, please help me for this code.

Since a is of type char*, a[i] is a char. k is a char too, thus you can simply compare them like this:
if(a[i] == k)
Moreover your scnafs' use the newline, discard it. Change this:
scanf("%c\n",&b);
to this:
scanf(" %c",&b);
where you should notice I left a space before %c, in order to eat a pending character (I have an example here).

If you test your functions it is better to create some test cases and avoid user input. This can be added later when you are sure that your function works.
Example (I do not know what n means in your example as you even do not declare it in your main :)
int s_replace(char *haystack, char needle, char replace, char flag) // a/A only first - any other complete
{
int result = 0;
if (haystack == NULL) result = -1;
if (!result)
{
while (*haystack)
{
if (*haystack == needle)
{
*haystack = replace;
if (!(result++) && tolower(flag) == 'a')
{
break;
}
}
haystack++;
}
}
return result;
}
int main()
{
int result;
char test[] = "Program question is: Write a C program to find and replace the character in the word. Here flag('A'/'F') indicates whether all occurrences has to be replaced or only the first occurrence has to be replaced.";
printf("Original string = \"%s\"\n", test);
result = s_replace(test, 'a', 'z', 'A');
switch (result)
{
case -1:
printf("Error !!!!!\n");
break;
case 0:
printf("Nothing was found. \n");
break;
default:
printf("Amended string = \"%s\"\n", test);
printf("Number of changes - %d\n", result);
}
return 0;
}

Related

C code acting weird. Sometimes, it takes input, sometimes it doesn't

I'm making a multi-feature command-line application where users have features like encrypt-decrypt a string, check string palindrome and reverse a string, and I started to write my whole code with the encrypt-decrypt feature, but apparently it is not working as expected, sometimes it encrypts/decrypts the string, the same code when executed again exits itself without taking the string input! I have even inserted the fflush(stdin), but no luck!
#include <stdio.h>
void encryptDecrypt();
// void checkPalindrome();
// void reverseWord();
void main()
{
int choice;
printf("\nWelcome to Jeel's multi-feature C App\n\n");
printf("1. Encrypt-Decrypt a word\t2. Check Palindrome\t3. Reverse a word\n\n");
printf("Enter a feature: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
fflush(stdin);
encryptDecrypt();
break;
case 2:
// checkPalindrome();
break;
case 3:
// reverseWord();
break;
default:
break;
}
}
void encryptDecrypt()
{
fflush(stdin);
char eOrD;
printf("\nWelcome to the World of Encryption & Decryption! We're so glad that you're here!\n\n");
printf("Enter 'e' if you want to encrypt a word or 'd' if you want to decrypt a word (e/d): ");
scanf("%c", &eOrD);
if (eOrD == 'e' || eOrD == 'E')
{
fflush(stdin);
char *word;
printf("\nGreat! Now enter a word to encrypt it: ");
fflush(stdin);
gets(word);
char *ptr = word;
for (int i = 0; i < sizeof(ptr); i++)
{
if (*ptr != '\0')
{
*ptr = *ptr + 7;
ptr++;
}
}
printf("\nEncrypted string is: %s, which is encrypted with the key: %d", word, 7);
}
else if (eOrD == 'd' || eOrD == 'D')
{
fflush(stdin);
char *deWord;
printf("\nGreat! Now enter a word to decrypt it: ");
gets(deWord);
char *dePtr = deWord;
for (int i = 0; i < sizeof(dePtr); i++)
{
if (*dePtr != '\0')
{
*dePtr = *dePtr - 7;
dePtr++;
}
}
printf("\nDecrypted string is: %s, which is decrypted with the key: %d\n", deWord, 7);
}
else
{
printf("Invalid input! Please try again!");
}
}
The best and most portable way to clear the stdin is using this:
void clearStream()
{
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}
Also the following is incorrect, create an array instead of the pointer:
char *word;
gets(word); //word is a pointer, gets will not create a block of memory for it

How can I monitor user input with getchar

I need to get a user input and check if it is a valid input.
The input must:
Start with space(may be multiple) or a number.
(Assuming condition one satisfied) After the number there may be any kind of characters as long as I manage to extract the number
Clarification for number valid values:
Can be multiple digit
Can't be negative number
Can't contain decimal point
Can't be scientific notation
Can't be hexadecimal
So I wrote this basic code which simply gets the input but I have no clue on where to start on applying these conditions
printf("Enter size of input:\n");
int c;
while((c=getchar())!='\n' && c!=EOF){
printf("%c",c);
}
For example :
Input - 4##2311413sadokalda ; expected output - 4
Input - !4a ; expected output - Invalid Size
You can have state machine as below.
printf("Enter size of input:\n");
int c;
int state = 0; //0 = space, 1 = number, 2 = number read
int number = 0;
while((c=getchar())!='\n' && c!=EOF){
switch(state)
{
case 0:
if (isdigit(c))
state = 1;
else if (c == ' ')
break;
else
//error
break;
case 1:
if (isdigit(c))
{
number = number*10 + (c-'0');
break;
}
else {
state = 2;
}
case 2:
printf ("%d\n",number);
}
}
You probably want something like this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
printf("Enter size of input:\n");
char input[100];
fgets(input, sizeof input, stdin);
if (!isdigit(input[0]))
{
printf("Invalid Size\n");
}
else
{
int inputsize = strtol(input, NULL, 10);
printf("%d\n", inputsize);
}
}
Based on the problem statement you have given, i think this should give you your desired output
EDITED (After a few clarifications):
int main()
{
int c;
int i=0;
while((c=getchar())!='\n' && c!=EOF)
{
if(isdigit(c) || (char)c==' ') //isdigit() function check if given variable is a digit
{ printf("%c",c);
i+=1;
}
else
{
break;
}
}
if(i==0)
{ printf("Invalid size"); }
}

Modify a function to return a pointer to the last letter in a word from a string

well I have problem with my exercise. I have a task that tell me that I have to modify a function (skipWords()) so that it instead of returning a pointer to the first letter in the chosen word, it returns a pointer to the last letter in the same word. Looks like I may not change anything in any other function than skipWords().
Here is an EXECUTION EXAMPLE:
Write a sentence: greetings to you
Which word do you want to print? 1
o
My code:
#include<stdio.h>
#include<strings.h> // We include this library to manipulate text strings.
#include<ctype.h>
#define SIZE 100
int printFirstWord(char *pointer)
{
int i;
int length=strlen(pointer);
for(i=0; i<length; i++)
{
if(isalpha(pointer[i])!=0)
{
printf("%c",pointer[i]);
}
else if(isalpha(pointer[i])==0)
{
break;
}
}
return 0;
}
char *skipWords(char sentence[],int words)
{
int count=0,x,i;
int length=strlen(sentence);
char *pointer;
if(words==0)
{
pointer=&sentence[0];
}
else
{
for(i=0; i<length; i++)
{
if(isalpha(sentence[i])==0)
{
x=i+1;
count=count+1;
pointer=&sentence[x];
}
if(i==(length-1))
{
pointer=NULL;
break;
}
if(count==words)
{
break;
}
}
}
return pointer;
}
void printWord(char sentence[], int wordNumber)
{
char *pointer;
int length;
length=strlen(sentence);
int i;
pointer=skipWords(sentence,wordNumber);
if(pointer==NULL)
{
printf("This word doesn't exist");
return ;
}
printFirstWord(pointer);
}
int main()
{
char sentence[SIZE];
int length;
int words;
int check=1;
while(check==1)
{
printf("Write a sentence; ");
gets(sentence);
length=strlen(sentence);
printf("\nWhich word should be printed? ");
scanf(" %d",&words);
printWord(sentence, words);
printf("\n Do you want to enter a new sentence (press 1 to say yes)?");
scanf("%d",&check);
getchar();
}
return 0;
}
My problem is that I'm not sure what I have to modify, I tried most of the afternoon and all my attempts to get it failed.
You are not allowed to have a Number inside your sentence, because isalpha only checks for Letters.
I changed some Variable names and used a fixed sentence and word but that doesn't change the program.
All I did (I think) was changing the printFirstWord fkt.
See the Code here:
http://coliru.stacked-crooked.com/a/df75d62b5aa338f3

Replacing a substring in a string - c

I'm trying to do a program which finds a substring in a string and replaces it with another substring entered by user. My code doesn't give a compile or run-time error, but it just doesn't work. I put printfs in the while loop which I wrote a comment line near it, and the program doesn't go into first if -I put another comment line near it. It prints a, h and i. The other parts in loop aren't working. Here's my code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *findAndReplace(char *sentence, char *word1, char *word2);
void main()
{
char sentence[1000];
char word1[200];
char word2[200];
int length;
printf("Please enter a sentence: ");
gets(sentence);
printf("Please write the word to be replaced: ");
gets(word1);
printf("Please write the word to be put instead: ");
gets(word2);
findAndReplace(sentence, word1, word2);
system("pause");
}
char* findAndReplace(char *sentence, char *word1, char *word2)
{
char *search, *tempString[1000];
int a, b, c, d, i = 0, j, sentenceLength, word1Length, searchLength;
sentenceLength = strlen(sentence);
printf("Length of %s is %d\n", sentence, sentenceLength);
printf("Finding ");
puts(word1);
search = strstr(sentence, word1);
searchLength = strlen(search);
word1Length = strlen(word1);
strcpy(tempString, sentence);
if(search != NULL)
{
printf("Starting point: %d\n", sentenceLength - searchLength);
}
else
{
printf("Eşleşme bulunamadı.\n");
}
j = 0;
while(j < sentenceLength + 1) //This loop
{
printf("a");
if(word1[i] == tempString[j])
{
printf("b");
if(i == word1Length)
{
c = j;
printf("c");
for(d = 0; d < word1Length; d++)
{
tempString[c - word1Length + d + 1] = word2[d];
printf("d");
}
i = 0;
j++;
printf("e");
}
else
{ printf("f");
i++;
j++;
}
printf("g");
}
else{
printf("h");
i = 0;
j++;
}
printf("i");
}
puts(tempString);
}
You've made a decent start, but you're making this a lot harder than it needs to be. One way to minimize errors is to rely on standard library functions when there are any that do the work you need done. For example:
char tempString[1000];
char *search;
search = strstr(sentence, word1);
if (search) {
ptrdiff_t head_length = search - sentence;
int sentence_length = strlen(sentence);
int word1_length = strlen(word1);
int word2_length = strlen(word2);
if (sentence_length + word2_length - word1_length < 1000) {
/* construct the modified string */
strncpy(tempString, sentence, head_length);
strcpy(tempString + head_length, word2);
strcpy(tempString + head_length + word2_length, search + word1_length);
/* copy it over the original (hope it doesn't overflow!) */
strcpy(sentence, tempString);
} else {
/* oops! insufficient temp space */
}
} /* else the target word was not found */
That covers only the search / replacement bit, fixing the error in tempString's type first pointed out by iharob. Also, it replaces only the first occurrence of the target word, as the original code appeared to be trying to do.
Among other things you have declared tempString as char* tempString[1000] which is an array of uninitialized character pointers so when you do
strcpy(tempString, sentence);
you are basically getting undefined behavior.
Use also fgets instead of gets when you input strings - even though you have rather large buffers it can happen one day that you pipe in a text file and get a stack overflow.
If I were you I would use strtok and split your sentence in words, then check each word. If word is same replace otherwise add sentence word to a new string.
e.g.
char newString[1000] = {0};
for (char* word = strtok(sentence, " "); word != NULL; word = strok(NULL, " "))
{
if (!strcmp(word, word1)) // here you may wanna use strncmp or some other variant
{
strcat(newString, word2);
}
else
{
strcat(newString, word);
}
strcat(newString, " ");
}
newString[strlen(newString)-1] = '\0';

Check if array of string A has letters that exist in array of string B (Not working)

my program currently has two strings, one which gets the user input from the users sentence he's entering (ASCI only) and the other is certain letters that i chose to compare the two strings with. My problem is that with using strncmp(), I'm trying to see if letters from the user input exist in the second array, and if they do, print "success", however when I run my program it appears to always print the noMatch function, even if i enter every letter present in my second array! Any help would be much appreciated!
Here is a snippet:
int main (void)
{
char letters[6] = {'a','b','c','d','e'};
char userInput[6];
printf("Enter a sentence! ASCII characters only!");
fgets(userInput,6,stdin);
doLettersMatch(userInput,letters);
}
void doLettersMatch(char userInput[], char letters[])
{
int i;
for(i=0;i<6;i++)
{
if(strcmp(&userInput[i],&letters[i]) != 0) //i.e letters don't match
noMatch();
}
printf("success! the letters matched from the user input");
}
int noMatch()
{
printf("No letters matched!");
return 0;
}
Your function should be:
void doLettersMatch(char userInput[], char letters[])
{
int i;
for(i=0;i<6;i++)
{
if(userInput[i] == letters[i]) {
++found;
printf("success! the letters matched from the user input");
return;
}
}
noMatch();
}
strcmp compares 2 strings and not letters. strcmp(&userInput[i],&letters[i]) will compare the substrings at offset i.
If you want to match the characters irrespective of the positions, use the following
void doLettersMatch(char userInput[], char letters[])
{
int i;
int j;
for(i=0;i<6;i++)
{
for(j = 0; userInput[j] != '\0'; ++j) {
if(userInput[j] == letters[i]) {
++found;
printf("success! the letters matched from the user input");
return;
}
}
}
noMatch();
}
This works for me (I think you dont want to compare the last char (\0)?) , as rusol said, comparing every char of the UserInput. It prints the position of the characters that are equal in both arrays:
void doLettersMatch(char userInput[], char letters[])
{
int i;
for (i = 0; i<6; i++)
{
if (userInput[i] == letters[i]){
printf("The character %c exists in both strings! Position: %d\n", letters[i], i);
}
}
}
int main(void)
{
char letters[6] = { 'a', 'b', 'c', 'd', 'e', 'f' };
char userInput[6];
printf("Enter a sentence! ASCII characters only!\n");
fgets(userInput, 6, stdin);
doLettersMatch(userInput, letters);
return 0;
}
Hope this helps!

Resources