In: Computer Science
Write a function bracket_by_len that takes a word as an input argument and returns the word bracketed to indicate its length. Words less than five characters long are bracketed with << >>, words five to ten letters long are bracketed with (* *), and words over ten characters long are bracketed with /+ +/. Your function should require the calling function to provide as the first argument, space for the result, and as the third argument, the amount of space available.
Program: C
Input:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *bracket_by_len(char*); // funtion declaration
int main() {
char string[20]; // expecting the string to be of 20letters
scanf("%[^\n]%*c", string); // taking string as input until enter is pressed
char a[20]; // to store the result string
strcpy(a,bracket_by_len(string)); // copying the returned string in a[]
printf("\n String is %s",a); //printing the new string with brackets
return 0;
}
char *bracket_by_len(char* string){ // funtion definition
int size = strlen(string) + 5; //calculating the size to allocate, here +5 is 4 for opening and closing brackets and 1 for buffer
char *str = malloc(size);
if(strlen(string)<5){ // checking for string length
strcpy (str, "<<"); // << will be copied to str
strcat (str, string); // string will be concatenated with str becoming <<String
strcat (str, ">>"); // >> will be concatenated with str becoming <<String>>
return str; // returning <<String>>
}
else if(strlen(string) >=5 && strlen(string) <=10){ // checking for string 5 to 10 letters long
strcpy (str, "(*"); // (* will be copied to str
strcat (str, string); // string will be concatenated with str becoming (*String
strcat (str, "*)"); // *) will be concatenated with str becoming (*String*)
return str; // returning (*String*)
}
else{ // This else will execute only if length is more than 10
strcpy (str, "/+"); // /+ will be copied to str
strcat (str, string); // string will be concatenated with str becoming /+String
strcat (str, "+/"); // +/ will be concatenated with str becoming /+String+/
return str; // returning /+String+/
}
}
Output: