Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to get the middle words of a string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

char* getMiddleWords(const char* string) {
    // Split the string into an array of words
    char* wordsArr[64]; // Assuming a maximum of 64 words
    int numWords = 0;
    char* token = strtok((char*)string, " ");
    
    while (token != NULL) {
        wordsArr[numWords++] = token;
        token = strtok(NULL, " ");
    }
    
    char* result = (char*)malloc(256 * sizeof(char)); // Allocate memory for result
    if (numWords % 2 == 0) {
        int middle1 = floor(numWords / 2) - 1;
        int middle2 = floor(numWords / 2);
        sprintf(result, "%s %s", wordsArr[middle1], wordsArr[middle2]);
    } else {
        int middle_minus_1 = floor(numWords / 2) - 1;
        int middle = floor(numWords / 2);
        int middle_plus_1 = floor(numWords / 2) + 1;
        sprintf(result, "%s %s %s", wordsArr[middle_minus_1], wordsArr[middle], wordsArr[middle_plus_1]);
    }
    
    return result;
}

int main() {
    char string[] = "c++ c java php c# python rust";
    
    char* middleWords = getMiddleWords(string);
    printf("%s\n", middleWords);
    
    free(middleWords); // Free allocated memory
    
    return 0;
}



/*
run:

java php c#

*/

 



answered Oct 8, 2024 by avibootz

Related questions

2 answers 90 views
1 answer 81 views
1 answer 93 views
1 answer 85 views
1 answer 90 views
1 answer 82 views
...