STRING - Remove small letters from string


Joined
Jan 20, 2023
Messages
1
Reaction score
0
#include <stdio.h>
#include <stdlib.h>
#include <cstring>

int odstranmale(char *str) {
int dlzka;
gets(str);
dlzka=strlen(str);

for (int i=1;i<=dlzka;i++)
if(str>='a' && str<= 'z')
str= str[i-1];
printf("Novy retazec %s",str);

return 0;


*************************************************************************************
Can someone tell me where is the mistake? I should get a string and remove small letters which appear in string and them print new string without these letters.
 
Ad

Advertisements

Joined
Jan 30, 2023
Messages
108
Reaction score
9
There are several mistakes in the code:

  1. gets function is dangerous and deprecated, it should be replaced by fgets.
  2. str>='a' && str<= 'z' is checking the first character of the string, not each individual character.
  3. str= str[i-1]; is overwriting the pointer instead of updating the string content.
  4. The updated string is not being returned.
Here is a corrected version of the code:

C:
#include <stdio.h>
#include <ctype.h>
#include <string.h>

void remove_lowercase(char *str) {
    int length = strlen(str);
    int j = 0;
    for (int i = 0; i < length; i++) {
        if (!islower(str[i])) {
            str[j++] = str[i];
        }
    }
    str[j] = '\0';
}

int main() {
    char str[100];
    fgets(str, 100, stdin);
    remove_lowercase(str);
    printf("New string: %s\n", str);
    return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top