Show only the last word of a string

1

The purpose of the program is to read a string , eg

read - Silva

printar

That is, always start the last word of string .

My logic was to read the string from back to front, and to find the first space to stop the loop.

In the example above, running in my program would look like:

1 - Read - Jose Da Silva
2 - Saving "avliS" in an string
3 - Then I create another loop and read back from the auxiliary string that would have "avliS" saved
4 - Back to front would be "Silva"

And finally I show the string that will have exactly the last word of the string typed.

Current situation of my code:

My code is able to read the string backwards and stop at the first (space) that it finds. But I do not know how to create a string that takes character from the last word of the first string (inverted), and then reverse that string > auxiliary.

NOTE: I am willing to see other logics (which may be easier than mine) to solve this problem.

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

int main (){
    char frase[200];
    int i;

    scanf(" %[^\n]s", frase);

    for (i=strlen(frase)-1;i> -1;i--){
        if (frase[i] == ' '){
            break;
        }

        printf("%c",frase[i]);
    }
    return 0;
 }
    
asked by anonymous 25.01.2018 / 19:17

2 answers

1

The logic is a bit different from the one proposed by you, but it works and (I think it's) simpler (although it reads the entire sentence, through the other method it would only read the word itself).

You're copying every% of% of the main phrase to another char of array , when you find some space, you "zero" that char , since having a space know that it is not the last word , at the end of the string it will be with the last word saved, then just end array with array and print.

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

int main (){
    char frase[200], palavra[50] = "";
    int i, j = 0;

    scanf(" %[^\n]s", frase);

    for(i = 0; frase[i] != '
#include <stdio.h>
#include <string.h>

int main (){
    char frase[200], palavra[50] = "";
    int i, j = 0;

    scanf(" %[^\n]s", frase);

    for(i = 0; frase[i] != '%pre%'; i++){
        palavra[j] = frase[i]; //usei o contador j em palavra pois ele poderá ser zerado ao encontrar espaço
        if(palavra[j] == ' ') //se encontrar espaço você começa uma nova palavra, mas continua onde parou na frase
            j = 0; 
        else //se não, você incrementa em j
            j++;
    }

    palavra[j] = '%pre%'; //finaliza o array e depois só imprimir

    printf("%s", palavra);
    fflush(stdin);
    getchar();

    return 0;
}
'; i++){ palavra[j] = frase[i]; //usei o contador j em palavra pois ele poderá ser zerado ao encontrar espaço if(palavra[j] == ' ') //se encontrar espaço você começa uma nova palavra, mas continua onde parou na frase j = 0; else //se não, você incrementa em j j++; } palavra[j] = '%pre%'; //finaliza o array e depois só imprimir printf("%s", palavra); fflush(stdin); getchar(); return 0; }

Corrected the loop as Maniero suggested below, making strlen() to any loop would actually spend processing, as long as it is different from %code% (until the end of the sentence) gets better.

    
25.01.2018 / 19:44
5

The simplest, most correct and most performative would be this:

#include <stdio.h>

int main () {
    char frase[200], palavra[200];
    scanf(" %[^\n]s", frase);
    int j = 0;
    for (int i = 0; frase[i] != '
#include <stdio.h>
#include <string.h>

int main () {
    char frase[200];
    scanf(" %[^\n]s", frase);
    printf("%s\n", strrchr(frase, ' ') + 1);
}
'; i++) { palavra[j] = frase[i]; j = palavra[j] == ' ' && frase[i + 1] != ' ' && frase[i + 1] != '
#include <stdio.h>

int main () {
    char frase[200], palavra[200];
    scanf(" %[^\n]s", frase);
    int j = 0;
    for (int i = 0; frase[i] != '
#include <stdio.h>
#include <string.h>

int main () {
    char frase[200];
    scanf(" %[^\n]s", frase);
    printf("%s\n", strrchr(frase, ' ') + 1);
}
'; i++) { palavra[j] = frase[i]; j = palavra[j] == ' ' && frase[i + 1] != ' ' && frase[i + 1] != '%pre%' ? 0 : j + 1; } palavra[j] = '%pre%'; printf("%s", palavra); }
' ? 0 : j + 1; } palavra[j] = '%pre%'; printf("%s", palavra); }

But if performance = more important has an even better way:

See running on ideone . And in Coding Ground . Also I placed GitHub for future reference . (note the additional blanks at the beginning, middle, and end).

I'm considering that you can have one huge word, so I kept the word size equal to the one in the sentence.

When using strlen() you need to scan the entire string and then scan again, and this is obviously a bad thing, so I'm stopping the loop when I find the terminator.

You are copying character by character from frase to palavra .

When there is a decision to change the value of the same variable in one form or another if a condition is true or false, it is usually better to use the conditional operator (I think it is a good learning, because it is practically just a change of syntax, the concept of condition you already understand).

The condition has to determine whether to clear the array counter of the word ( j ) should be incremented. If it is not incremented, it must be zeroed, ie forget everything you were saving and start again in the array of the word. But there's some catch-ups there.

If it is a blank space, theoretically it should reset the counter because a new word begins. But in fact the word only begins if the next one is a nonwhite character. So besides being a white the next should be a non-white.

And also can not have it terminated (null character palavra ), since this would affect the index counter of , and we need to know where it is to put the terminator.

If these conditions are not observed, additional blanks give the wrong result.

We need to put a terminator in the array that receives the word, otherwise its potential will have no end and access memory it should not.

Then it prints the word according to the selected one. But it has a defect because if it has space at the end the space will be printed. You can set this up, but you had nothing in the question to indicate that you need it.

Another failure is if you find a tab or other blank character that separates words, or if you find a separator symbol, such as punctuation ( . , ? , strrchr() , etc.), but it may be being used so as not to separate words, then everything gets much more complicated to solve.

But if it is not important to check these cases for additional spaces, then one line resolves:

%pre%

The function %code% just takes the last block separated by some character.

    
25.01.2018 / 20:12