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,950 questions

51,892 answers

573 users

How to find the length of the second smallest word in a string with C

2 Answers

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

int secondSmallestWordLength(char *str) {
    char *arr = strtok(str, " ");
    int count = 0;
    int *lengths = NULL;

    while (arr != NULL) {
        count++;
        lengths = realloc(lengths, count * sizeof(int));
        lengths[count - 1] = strlen(arr);
        arr = strtok(NULL, " ");
    }

    if (count < 2) {
        free(lengths);
        return -1;
    }

    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (lengths[j] > lengths[j + 1]) {
                int temp = lengths[j];
                lengths[j] = lengths[j + 1];
                lengths[j + 1] = temp;
            }
        }
    }

    int result = lengths[1];
    
    free(lengths);
    
    return result;
}

int main() {
    char *str = "java c++ python c# c javascript";
    
    printf("%d\n", secondSmallestWordLength(str));
    
    return 0;
}


 
    
          
/*
run:
       
name: C-3PO     age: 137     language: ALL     location: Tatooine
  
*/

 



answered Jun 4, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare(const void *a, const void *b) {
   return ( *(int*)a - *(int*)b );
}

int secondSmallestWordLength(char str[]) {
    char *arr = strtok(str, " ");
    int count = 0;
    int *lengths = NULL;

    while (arr != NULL) {
        count++;
        lengths = realloc(lengths, count * sizeof(int));
        lengths[count - 1] = strlen(arr);
        arr = strtok(NULL, " ");
    }

    if (count < 2) {
        free(lengths);
        return -1;
    }
    
    qsort(lengths, count, sizeof(int), compare);

    int result = lengths[1];
    
    free(lengths);
    
    return result;
}

int main() {
    char str[] = "java c++ python c# javascript";
    
    printf("%d\n", secondSmallestWordLength(str));
    
    return 0;
}

    
          
/*
run:
       
3
  
*/

 



answered Jun 4, 2024 by avibootz

Related questions

...