-4

I need to sort each word in a sentence alphabetically while keeping the words separate from one another. I am not allowed to use the strtok() function.

Sample input: I would really appreciate some help

Sample output: I dlouw aellry aaceeipprt emos ehlp

I have managed to sort the entire string alphabetically.Which gives me an output of: Iaaacdeeeeehillllmooppprrstuwy

I am not sure If I should nest my current code into a loop which would start over every time there is a space. Or if I need to read my string into a two-dimensional array and sort each word separately.

I am also not sure if it would make more sense to compare the values of each char or to count the occurrence of each letter within the string. I have a version of each which gives me the output shown above.

Thanks in advance.

Version comparing chars:

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

int main () {

    char str[100];

    printf("Please type a sentence :\n");
    scanf("%[^\n]s", str);

    printf("\nAlphabetical order:\n:);

    char temp;

    int i, j;
    int n = strlen(str);

    for (i = 0; i < n-1; i++) {
        for (j = i+1; j < n; j++) {
            if (str[i] > str[j]) {
                temp = str[i];
                str[i] = str[j];
                str[j] = temp1;
            }
        }
    }

    printf(str);

    return 0;
}

Version counting occurrences of each char:

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

int main () {

  char ch, input[100], output[100];
  int no[26] = {0}, n, c, t, x;

  printf("Please type a sentence:\n");
  scanf("%s", input);

  n = strlen(input);

  for (c = 0; c < n; c++)
  {
    ch = input[c] - 'a';
    no[ch]++;
  }

  t = 0;

  for (ch = 'a'; ch <= 'z'; ch++)
  {
    x = ch - 'a';

    for (c = 0; c < no[x]; c++)
    {
      output[t] = ch;
      t++
    }
  }
  output[t]  = '\0';

  printf("%s\n", output);

  return 0;

}
  • 5
    Is this job about searching solutions online, or about solving problems? – Eugene Sh. Apr 05 '19 at 21:12
  • get word, sort word, add to builder string, repeat. – NathanOliver Apr 05 '19 at 21:13
  • 1
    The c++ solution compiles fine for me if I add the headers and `std::`s. It also seems to work, except that the words are separated by line breaks instead of spaces. It's not clear what you are asking. Are you just asking which headers are missing? – François Andrieux Apr 05 '19 at 21:14
  • 4
    No offense but if you can't solve the problem you're given to apply with, you're applying for the wrong job. – Vulpex Apr 05 '19 at 21:18
  • 2
    Asking questions on topics like these are fine. But prefacing it by saying that this is for a job application is not a good idea. The employer wants to see how you solve the problem, not how others on the internet solve the problem. – Kevin Vandy Apr 05 '19 at 21:20
  • 1
    I realize I should be able to solve this for myself. The job aside, I would like to understand how to solve this problem. I don't see an identical problem on here, so any answer would benefit the community. – scottdavisxx Apr 05 '19 at 21:24
  • The way I would solve this would be to separate each word in an array, do the sort on each word, then concatenate the elements back together. – Kevin Vandy Apr 05 '19 at 21:27
  • C and C++ are two different languages with different ways of solving problems. So if you ask a question you should decide for which language you want to have the answer. So if you tag it as `c` then remove the c++ code and limit your self to `c` for this question. – t.niese Apr 05 '19 at 21:39
  • I am new here. I am just looking for some help. I have made some revisions to my post based on feedback. I only tagged C language and removed the C++ solution. – scottdavisxx Apr 05 '19 at 21:40

3 Answers3

0

std::sort will sort any sequence you give it. E.g.

std::sort(str.begin(),str.begin()+5);
std::sort(str.begin()+6,str.end());
std::cout<<str;

Should output Hello dlorw. You can put custom comparison operator if you want to treat upper case letter differently.

Now you only have to iterate over the words. Please don't randomly mix C++ and C.

Quimby
  • 17,735
  • 4
  • 35
  • 55
0

The standard library has enough facilities for you not to need to write any loop of your own. See:

How do I tokenize a string in C++?

about working with words and

The C++ standard algorithms library

for sorting etc. Oh, you might also want to read up on iterators.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
0

Read user input with fgets(). Validate success before attempting to use input.

char buffer[1024];
if (fgets(buffer, sizeof buffer, stdin)) {
  const char *s = buffer;

Search for letters. Use isalpha().

  while (*s) {
    while (!isalpha((unsigned char)*s) && *s) {
      putchar(*s);
      s++;
    }
    const char *start = s;
    while (isalpha((unsigned char)*s)) {
      s++;
    }

Sort with qsort() and print using a precision. Now s does not need to be null character terminated. Avoid sizeof(type) and use sizeof *pointer as it is easier to code right, review and maintain.

    int len = s - start;
    qsort(start, len, sizeof *start, fcmp);
    printf("%.*s", len, start);
  }
}

fcmp() simply compares characters. The standard library tends to treat the value of char as the value once it is converted to unsigned char.

int fcmp(const void *va, const void *vb) {
  const unsigned char *a = va;
  const unsigned char *b = vb;
  return (*a > *b) - (*a < *b);
}

Code could have used return a - b;. The above is more idiomatic and never involves int overflow (Unlike those rare machines with CHAR_MAX > INT_MAX).

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256