Use functions to convert string to upper and lowercase in C - c

This is homework and this is the task I was given:
Prints the string in uppercase and lowercase
Splits the string on the middle and prints the two parts with " - " between
Requirements:
Converting the string to upper and lower case must be done in functions. These functions must return nothing (void) and be called: string_upper, string_lower.
Do not use strlwr or strupr.
Note: The string length is always even.
Expected output (with the string you receive as input):
The string in uppercase is 'ABCDEFGH'
The string in lowercase is 'abcdefgh'
The string split in two is 'abcd - efgh'
I have managed to come up with something that works but it dosent use functions as requiered in the task. How can you do this with funtions?
I have looked around but I cant find any examples of converting strings to upper and lowercase using functions
#include<stdio.h>
#include<string.h>
int main() {
char inputString[100], leftHalf[100], rightHalf[100];
int length, mid, i, k;
/* Read input string from user using gets */
printf("Enter a string\n");
gets(inputString);
/* Find length of string using strlen function */
length = strlen(inputString);
mid = length/2;
/* Copy left half of inputString to leftHalf */
for(i = 0; i < mid; i++) {
leftHalf[i]= inputString[i];
}
leftHalf[i] = '\0';
/* Copy right half of inputString to rightHalf */
for(i = mid, k = 0; i <= length; i++, k++) {
rightHalf[k]= inputString[i];
}
for(i=0;i<=strlen(inputString);i++)
{
if(inputString[i]>=65&&inputString[i]<=90)
inputString[i]=inputString[i]+32;
}
printf("String in Lowercase: %s\n",inputString);
/* To print string in upperCase*/
for(i=0;i<=strlen(inputString);i++)
{
if(inputString[i]>=97&&inputString[i]<=122)
inputString[i]=inputString[i]-32;
}
printf("String in Uppercase: %s\n",inputString);
/* Printing left and right half of string */
//printf("Left half : %s\n",leftHalf);
//printf("Right half : %s\n",rightHalf);
printf("%s-%s",leftHalf, rightHalf);
return 0;
}

To create a function, just remove the code (e.g. the for-loop) to a function. Don't forget to declare auxiliary variables (e.g. int i). Like so
void string_upper (char *inputString)
{
int i;
for(i=0;i<=strlen(inputString);i++)
{
if(inputString[i]>=65&&inputString[i]<=90)
inputString[i]=inputString[i]+32;
}
}
And then in your main code, you call
string_upper (inputString);
instead of the for-loop that was there.
Do the similar for string_lower.

You can just put your code to convert the string to upper and lower case in separate functions. like this.
void string_upper (char* str) {
for(int i=0; i<=strlen(str); i++) {
if(str[i]>=97 && str[i]<=122)
str[i]=str[i]-32;
}
}
void string_lower(char* str) {
//...
}
int main() {
char inputString[100], leftHalf[100], rightHalf[100];
int length, mid, i, k;
//...
/* call function to convert string to upper-case*/
string_upper(inputString);
printf("String in Uppercase: %s\n",inputString);
/* call function to convert string to lower-case */
string_lower(inputString);
printf("String in Lowercase: %s\n",inputString);
//...
return 0;
}

If you're allowed to use tolower() and toupper(), this works:
#include <ctype.h>
// note unsigned char!
void string_upper( unsigned char *str )
{
while ( *str )
{
*str = toupper( *str );
str++;
}
}
string_lower() is left as an exercise for the reader... ;-)

Related

C programming. Function to generate a string of random letters using only arrays and then pointers

Im trying to code a program in C to generate a string containing random letters using only arrays first and then again using pointers. I've looked at many other questions but is not quite what I'm trying to accomplish. I can really use help please.
Function 1- Generates a string with random upper
case letter A-Z with 40 characters.
Function 2- Function to let user enter a string
with random upper case letter and a replacement character.
Function 3- Searches string1 from function 1 and replaces
occurences of any character from string 2 (user entered) with
replacement character.
OUTPUT EX.
String 1- "AABBCCDDEEFFGGHHABCDEFGH"
String 2- "BE"
Replacement char- "3"
Filtered string- AA33CCDD33FFGGHHA3CD3FGH.
This is what I have so far, Im not very good with arrays.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int s1 [41];
srand(time(NULL));
int i;
for (i = 0; i < 41; i++)
{
s1 [i] = rand();
}
return 0;
}
Any help will be appreciated.
Thanks alot.
#include <stdio.h>
#include <stdlib.h>
void rand_str(char* txt, size_t sz)
{
int i=sz-1;
while( i --> 0 )
{
txt[i] = 'A' + rand() % 26;
}
printf("Random Str: %.*s\n", sz+i, txt);
}
void fn2(char* tgt, size_t sz, char* repl )
{
puts("String 2: ");
fgets(tgt, sz, stdin);
puts("Replacement Char: ");
*repl = getchar();
}
void search_replace(char* txt, char* tgt, char repl)
{
while(*tgt != '\0')
{
while ((strchr(txt, *tgt) ? (tgt[strchr(txt, *tgt)-tgt] = repl) : 0) == repl);
tgt++;
}
}
int main(void)
{
char txt[41] = {0};
char tgt[40] = {0};
char repl;
rand_str(txt, sizeof(txt));
fn2(tgt, sizeof(tgt), &repl);
search_replace(txt, tgt, repl);
return !printf("Filtered String: %s\n", txt);
}
Please note that I did not compile any of this code. It might have some typo and/or runtime errors. The concept is correct though and you should understand the code first and not just copy it.
Function 1:
#include <stdlib.h> // Important! rand() function that generate random function is in that library!
//This function returns a pointer of an array (arr). In other words it returns the **address** of the first character of the array.
// Assuming arr is valid!
char* randomString(char* arr){
// This part does not REALLLYY matters it just makes sure the random will truly be random...
time_t t;
srand((unsigned) time(&t)); // Seeds the random function.
//------------------
//Looping the array assigning random letters:
int i = 0;
while(i<SIZE){
arr[i] = 'A'+(rand()%('Z'-'A'+1));// 'A' has a numerical value, we want the range from 'A' to 'Z' to be random. 'Z'-'A' is the range of letters (26) because its a modulu if the modulu was just 'Z'-'A' (26) it wouldnt print Z. 'Z' is the 26th letter, 26%26 is zero, it will not give 'Z' this is why I increased 'Z'-'A' by 1 so the modulu will include 'Z' as random latter.
i = i + 1;
}
arr[i] = 0;// String terminator also called NULL.
return "lol";
}
Function 2:
#include <string.h>
int replace(char* inputString, char* userInput,char replacement ){
/* e.g.
inputString = "ABSDSADASBBBAA";//Generate yourself... (Might want to user function 1)
userInput = "AB"; // You need to do the user input yourself...
replacement = 'D';
*/
int i = 0;
while(i<strlen(inputString)){
int j = 0;
while(j<strlen(userInput)){
if(inputString[i]==userInput[j]){
inputString[i] = replacement;
}
j = j+1;
}
i = i + 1;
}
}
Function 3:
int main(){
// Just use regular IO libraries to get user's input...
// Assuming you did that, I will hard code the values (you need to do the IO e.g. gets())
char str[SIZE];
randomString(str); // Requirement #1 reuse of function 1
char * userInput = "AB"; // You need to do the user input yourself...
char replacement = 'D';// You need to do the user input yourself...
replace(str, userInput, replacement)//Requirement #2
return 0;
}

Issue with Strings in C

Here is a program with Strings where I am trying
Pig Latin translation is simply taking the first letter of a “word” and appending that letter to the end of the word with “ay” added to the end as well
I have issue with m1=m2+3 ( resetting the Initial Marker ).
Input that I am giving : "Alex, how are you right"
The output I am expecting is : lexay, owhay reay ouyay ightray
But
I am getting this : lex,Aay way ay ayo gayi
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void initialize(char english[], char piglatin[]);
void readinput (char english[]);
int countwords(char english[]);
void convert ( int words, char english[], char piglatin[]);
void writeoutput( char piglatin[]);
int main()
{
char english[80], piglatin[80];
int words;
initialize(english, piglatin);
printf("enter the string\t");
fflush(stdin);
gets(english);
printf ("\nInput buffer contents: %s\n", english);
words = countwords(english);
convert(words,english,piglatin);
writeoutput(piglatin);
printf ("Have a nice day\n");
}
void initialize(char english[], char piglatin[])
{
int count;
for(count =0; count<80;++count)
{
english[count]=piglatin[count]=' ';
}
return;
}
/* Scan the english test and determine the number of words */
int countwords(char english[])
{
int count, words =1;
for ( count =0;count <79;++count)
{
if(english[count]==' ' && english[count+1]!=' ')
++words;
}
printf("%d\n",words);
return (words);
}
/* convert each words in to piglatin*/
void convert ( int words, char english[], char piglatin[])
{
int n, count;
int m1=0;
int m2;
/* convert each word */
for ( n=1;n<=words;++n)
{
/* locate the end of the current word*/
count = m1;
printf ("\ before conversion word contents: %d\n", count);
while ( english[count]!=' ')
{
m2=count++;
}
printf ("\ before conversion word contents: %d\n", m2);
/* transpose the first letter and add 'a', 'y'*/
for (count =m1;count<m2;++count)
{
piglatin[count+(n-1)]=english[count+1];
}
piglatin[m2+(n-1)] = english[m1];
piglatin[m2+1] = 'a';
piglatin[m2+2] = 'y';
m1=m2+3;
printf ("\ Converted word contents: %s\n", piglatin);
}
return;
}
void writeoutput( char piglatin[])
{
int count =0;
for (count =0; count <80; ++count)
{
putchar(piglatin[count]);
}
printf ("\n");
return;
}
I see various problems here:
Alex -> lex,Aay: You should check for punctuation marks when determining the end of the words, thus inserting the Aay part before the comma character
Alex -> lex,Aay: Every character from the start of a word should be converted to lowercase and the resulting first character should be converted to upper case respectively
Now the conversion function: I have changed it a bit to get you started; it should work now ( at least it does with your test string ) without taking 1 and 2 into account though
void convert(int words, char english[], char piglatin[])
{
int estart = 0;
int ppos = 0;
int m2;
for (int n = 0; n < words; n++)
{
//locate the start of the current word, to make
//sure something like this is converted:
//"Alex, how are you"
while (english[estart] == ' ')
{
//make sure we do not exceed the strings boundaries!
if (english[estart] == '\0')
{
return;
}
estart++;
}
//locate the end of the word
int eend = estart;
while (english[eend] != ' ')
{
//never forget to check for the end of the string
if (english[eend] == '\0')
{
break;
}
eend++;
}
/* transpose the first letter and add 'a', 'y'*/
for (int i = estart+1; i < eend; i++, ppos++)
{
piglatin[ppos] = english[i];
}
piglatin[ppos++] = english[estart];
piglatin[ppos++] = 'a';
piglatin[ppos++] = 'y';
//dont forget to add a whitespace or your string might behave
//very stangely!
piglatin[ppos++] = ' ';
estart = eend;
printf("\ Converted word contents: %s\n", piglatin);
}
}
I hope this gets you started in the right direction.
Please also check your array sizes for english and piglatin. The string for piglatin is alway longer than the english one but your array sizes are the same! Also i would advise you add some boundary checks to make sure you do not leave the array boundaries.

Count number of consonants in a string

Another starter question.
int counterConstant;
int x;
for(x = 0; x<20; x++){
if("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSVWXYZ".IndexOf(tempString[x]) >= 0){
counterConsonant++;
}
}
But I get an error:
"error: member reference base type 'char [42]' is not a structure or union"
Is there another way I could do this?
(I'm doing this inside a for that checks each char on the string.)
There are no objects in C, so there are no "methods" and you can't call IndexOf on a string literal. A string is nothing more than an array of characters in C.
With that in mind, let's see how you can actually loop over the characters of a string:
for (const char *p = tempString; *p != '\0'; ++p) {
/* loop body */
char c = *p; // *p is the current letter
}
This will create a pointer to the first element of the string, and then loop over all of the following characters, if you'd really prefer to use indexes, you could do
for (size_t i = 0, len = strlen(tempString); i < len; ++i) {
char c = tempString[i];
}
As far as checking each letter for consonant-ness, that you can write a helper function for
int is_consonant(char c) {
c = tolower(c); // #include <ctype.h>
if (!isalpha(c)) return 0; // if not a letter, return false
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 0;
default:
return 1;
}
}
now back to your loop, use this function to check each character.
int consonant_count = 0; // the =0 is important!
for (const char *p = tempString; *p != '\0'; ++p) {
if (is_consonant(*p)) {
++consonant_count;
}
}
If you don't initialize to 0, the initial value of consonant_count is unpredictable, so make sure you do.
If you are working on C (as it was specified in tags), strchr() method is used to search a char in a string, and strstr() is used to search a string in a string. We will use strchr() here because tempString[x] is a char. Also, don't forget to give your int variable an initial value. Try this code:
int main()
{
int counterConsonant = 0;
int x;
const char* tempString = "12345678901234567890";
for (x = 0; x<20; x++){
if (strchr("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSVWXYZ", tempString[x]) != NULL){
counterConsonant++;
}
}
return 0;
}
C is a structured procedural language, so it doesn't have member functions/methods like a "true" object-oriented programming language such as C#. You could use a combination of strspn and strcspn like below to count sequences of consonants and non-consonant characters respectively, based on a predefined list of consonant characters:
#include <string.h>
size_t
count_consonants (const char *s)
{
size_t n;
size_t total = 0;
const char *consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
/* While we haven't reached the end of the string,
execute the code in the body of the loop. */
while (*s != '\0')
{
/* Count the number of consonants starting at the current string position. */
n = strspn (s, consonants);
/* Add the number of consonants counted to
the total number of consonants found. */
total += n;
/* Advance the character pointer to the next character
that IS NOT a consonant, based on the number of consonants
stored in `n'. */
s += n;
/* Advance the character pointer to the next character
that IS a consonant (`strcspn' = skip the characters in
`s' that don't appear in `consonants'). */
s += strcspn (s, consonants);
}
return total;
}
char temp[20];
scanf("%s",temp);
int i,j, consonantsCounter=0;
char consonants[]={'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z','B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','V','W','X','Y','Z'}
for(i=0;i<20;i++){
for(j=0;j<(sizeof consonants) / (sizeof consonants[0]);j++){
if(temp[i]==consonants[j]){
consonantsCounter++;
}
}
}

Reading Both Individual Characters of Strings and the Strings themselves Pointed to by a String Array

In the code below, I'm attempting to pass the string array 'char *wordArray[20]..." into the function above main that is intended to find all strings within wordArray that contain a user-input character, and print each such string. Function "findWords" is defined to expect a constant string array, its length and the user-input character because the array will be read-only. Following examples from the text I'm using, the bottom is a combination of methods for reading individual characters from a pointer to a string, and for reading strings from a pointer array.
#include <stdio.h>
#include <stddef.h>
#include <ctype.h>
int arrLength = 0; // Global variable dec. and initialization
void findWords ( const char *c[], int length, char letter ) {
size_t element = 0;
size_t count = 0;
for (element = 0; element < length; element++) {
for (count = 0; c[count] != '\0'; count++) {
if (c[count] == letter) {
printf("%s", c[element]);
}
else {
printf("%s", c[count]);
}
}
count++;
}
return;
} // End function findWords
int main (void) {
{ // Begin Problem 3
// step 1: printf "Problem 3"
puts("Hiya");
// step 2: create a string array of 3 pointers to strings containing at this point, random
words.
const char *wordArray[3] = { "cake", "foxtrot", "verimax" };
char usrInp; // Holds user-input letter.
// step 3: "Input a letter from the user."
// This do...while loop repeats until the user has entered either a lower- or uppercase
letter.
do {
puts("Please enter one lowercase letter - any you'd like\n"); // One string argument
calls for output function puts(); rather than printf();
usrInp = tolower ( getchar() );
} while ( isalpha (usrInp) == 0 );
findWords( wordArray, arrLength, usrInp );
} // End Problem 3
} // End function main
at findWords :
for (element = 0; element < length; element++) {
for (count = 0; c[element][count] != '\0'; count++) {
if (c[element][count] == letter) {
printf("%s\n", c[element]);
break;
}
}
}
at main :
arrLength = sizeof(wordArray)/sizeof(*wordArray);//arrLength = 3;
findWords( wordArray, arrLength, usrInp );
c[count] is char* which means you cannot compare it to a char. this pointer just holds the address to your current string. you need to traverse that string in order to check for letter.
In your code you need to change:
if (c[element][count] == letter)

Find the number of occurrence of each character in a string In C

I have a problem in C where i have to find number of occurrence of each character in a string.Suppose i have string like "amitamt" and output should be like "a2m2it2" .I have a routine from which i can find no of occurrence of a particular character.
int count_chars(const char* string, char ch)
{
int count = 0;
int i;
int length = strlen(string);
for (i = 0; i < length; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
But I am not sure how could I count each character of string
If you have an ASCII string, create an int array of size 256. Then loop through the string and increment the value in the int array on position x. While x is the ASCII value of the character in your string you're looping through.
if i have any mistakes like syntax please excuse as im working on vb , Im unable to figure out where to put braces or brackets ,
and I belive strchr makes your task easier
#include <stdio.h>
#include <string.h>
int str_occ (char *pch ,char a)
{
int i = 0;
char *p;
p=strchr(pch,a);
while (p!=NULL)
{
i = i+1;
p = strchr(p+1,a);
}
return i;
}
To explain the code *pch is the string you have to pass ,char a is the alphabet you are searching to find how many times its occurring and int i returns the value of number of occurrences
say sample
int main()
{
char a[]="hello world";
int i;
i=str_occ(a,'l');
printf("%d",i);
}
output is 3
You can make the code as per your requirements, keep caling the function inside a loop , I mean rotate your elements

Resources