In: Computer Science
(C LANGUAGE) Write a function called upperLower that inputs a line of text into char array s[100]. Output the line in uppercase letters and in lowercase letters
This is what I have so far:
void * upperLower (const char * s) {
char *word[sizeof(s)];
for(int i = 0; i < sizeof(s); i++){
*word[i] = s[i];
}
word = strtok(word, " ");
int counter = 0;
while(word != NULL){
if(counter % 2 == 0){
word[counter] = toupper(word);
printf("%s ", word);
}
else{
word[counter] = tolower(word);
printf("%s ", word);
}
counter++;
word = strtok(NULL, " ");
}
}
The method cannot be changed. Must use void * upperLower (const char * s) {
The output should be like THIS is A test
Note: The complete code is provided using the given function. The language used is C.
Code:
#include<stdio.h>
#include<string.h>
void * upperLower (const char * s){
//Length of string s
int n = strlen(s);
//New string which is the answer.
char answer[n];
int i;
//Copy the string s to answer.
for(i=0;i<n;i++)
answer[i] = s[i];
//Capital is a variable which checks whether a particular
//character should be converted to capital or small letters.
int capital = 1;
for(i=0;i<n;i++){
//If we encounter space, change the capital variable.
if(answer[i] == ' '){
if(capital == 1)
capital = 0;
else
capital = 1;
continue;
}
//If capital is 1, change each English alphabet to capital
letter
//Else change each English alphabet to small letter
if(capital == 1){
if(answer[i]>='a' && answer[i]<='z'){
//ASCII code of a is 97 and A is 65. So there is a difference of
32.
answer[i]-= 32;
}
}else{
if(answer[i]>='A' && answer[i]<='Z'){
answer[i]+=32;
}
}
}
printf("The required string is:\n%s\n", answer);
}
//Main function.
int main(){
const char *s = "This is a test";
upperLower(s);
return 0;
}
Code Snippets:
Sample Output: