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 print the middle words of a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
 
void printMiddleWords(char *s) {
    int i = 0;
    int len = strlen(s);
     
    // Skip the first word
    while (i < len && s[i] != ' ') {
        i++;
    }
     
    char word[32]; // Assuming no word is longer than 32 characters
    int word_index = 0;
     
    for (i++; i < len; i++) {
        if (s[i] != ' ') {
            word[word_index++] = s[i];
        } else {
            word[word_index] = '\0';
            printf("%s ", word);
            word_index = 0;
        }
    }
}
 
int main() {
    char s[] = "c++ c java python rust";
     
    printMiddleWords(s);
     
    return 0;
}
 
 
  
/*
run:
  
c java python 
  
*/

 



answered Oct 7, 2024 by avibootz
edited Oct 7, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void printMiddleWords(char *str) {
    char *words[64]; 
    int count = 0;
    
    // Split the string into words
    char *token = strtok(str, " ");
    while (token != NULL) {
        words[count++] = token;
        token = strtok(NULL, " ");
    }
    
    if (count % 2 == 0) {
        printf("Middle words: %s %s\n", words[count / 2 - 1], words[count / 2]);
    } else {
        printf("Middle word: %s\n", words[count / 2]);
    }
}

int main() {
    char str[] = "c++ c java python c# rust";
    
    printMiddleWords(str);
    
    return 0;
}


 
/*
run:
 
Middle words: java python
 
*/ 

 



answered Oct 7, 2024 by avibootz
...