1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

C language. work with text

Discussion in 'Programming' started by dimchas, Dec 9, 2021.

  1. #1
    hello, I just recently started learning C language. Please do not swear at me))

    i want to make a program
    I enter text from the keyboard into the console and I want the program to swap the first and last letter of each word and count how many words are in the sentence.
    I found a program on the Internet that swaps letters and altered it a little
    how can i fix it?
    I did it but he only counts the words

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>


    char * swap(const char * str);

    int main(void)
    {
    char s[200];
    int count = 0, i;
    printf("Enter the string:\n");
    scanf("%[^\n]s", s);
    for (i = 0;s != '\0';i++)

    {
    if (s == ' ' && s[i+1] != ' ')
    count++;
    }
    printf("words: %d\n", count + 1);
    }

    char * swap(char * s)
    {
    const size_t length = strlen(s);
    char * ch = malloc(length + 1);

    strncat(ch, s, length);
    ch[length] = '\0';

    char * k = ch;

    while (k != NULL)
    {
    char * last = strchr(k, ' ');

    if (last != NULL)
    {
    char t = *k;
    *k = *(last - 1);
    *(last - 1) = t;
    k = last + 1;
    }
    else
    {
    char t = *(k);
    *k = *(ch + length - 1);
    *(ch + length - 1) = t;
    k = NULL;
    }
    }

    return ch;
    }
     
    dimchas, Dec 9, 2021 IP