Problem accessing array element

3

I have a problem with the function below that truncates all words so that they have a maximum of N characters.

For example: if the string contains: "freedom, equality and fraternity", the invocation of truncW(t,4) should give "libe equal and frat".

This is what I got:

void truncW (char t[], int n)
{
  int j ;

   for ( j = 0 ; j < n ; j++)      
   {
    if ( isspace (t[j]) == 0 )
    { printf ("%c " , t[j]);}
   }
}

void main ()
{
   char t[] = "liberdade, igualdade e fraternidade";
   truncW (t,4);
}

output gives only: "libe"

I would like to know how to scroll through the entire list and get at most n characters of each word . What's missing in the code to allow this?

    
asked by anonymous 15.03.2015 / 19:34

4 answers

4

Your biggest problem is here:

for ( j = 0 ; j < n ; j++) 

This means that you will only scroll through the first% w / o% characters of the string, not each word.

I think the best way to do this is by having an accountant count how many letters in a word you've seen, and zeroing it out whenever you find the space. You use the counter value to decide whether to print the letter or not.

I did it and it worked:

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

void truncW(char t[], int n)
{
    int len = strlen(t);
    int j;
    int letras_consecutivas = 0;

    for (j = 0; j < len; j++)   
    {
        if (isspace(t[j]) == 0)
        {
            letras_consecutivas++;
        } else {
            letras_consecutivas = 0;
        }
        if (letras_consecutivas <= n) {
            printf("%c", t[j]);
        }
    }
}

int main()
{
    char t[] = "liberdade, igualdade e fraternidade";
    truncW(t, 4);
    return EXIT_SUCCESS;
}
    
15.03.2015 / 19:51
4

You still have to scroll through the string until you find another space (or the end of the string) and - if you found a space - start all over again. Instead of making the loop from 0 to n , make 0 to the end of the string, and use a separate count to go from 0 to n (resetting this count every time you find a space ):

int j;
int contagem = 0; // Quantas letras você já tirou da palavra

for ( j = 0 ; j < strlen(t) ; j++ ) // Percorre a string inteira, não só os n primeiros
{
    if ( isspace (t[j]) == 0 && contagem < n ) // Se é letra e ainda não tirou tudo
    { 
        printf ("%c " , t[j]); // Tira
        contagem++;            // E incrementa a contagem
    }
    else if ( isspace (t[j]) != 0 ) // Se é espaço
        contagem = 0;               // Reseta a contagem, pra consumir outra palavra
}

Note: This example prints only letters from words, not spaces between them (ie output will be libeiguaefrat ). If you also want to print the spaces, see Victor Stafusa's answer .

    
15.03.2015 / 19:51
3

You were not sweeping across the string and still was not restarting the count of the limit characters of each word. I would do so:

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

void truncW (char t[], int n) {
    int s = strlen(t); //acha o tamanho da string
    //cria dois contadores aqui, o i que varre **toda** a string e o j que vai até n
    for (int i = 0, j = 0; i < s; i++, j++) {
        if (isspace(t[i]) > 0) { //se achou um espaço em branco
            j = -1; //reseta o contador de caracteres já que vai começar outra palavra
            printf(" "); //dá um espaço
        } else if (j < n) { //se ainda não atingiu o limite de caracteres por palavra
            printf("%c", t[i]); //imprime o caractere
        }
    }
}

int main(void) {
   char t[] = "liberdade, igualdade e fraternidade";
   truncW(t, 4);
}

See running on ideone .

Note that e appears, if it can not appear it should have a clear rule about it.

    
15.03.2015 / 19:58
2

Using flex (flex generates C and is optimal for programming textual processing):

%option noyywrap

%%
[a-z]{4,}     { yyleng=4 ; ECHO; }   
.|\n          {            ECHO; }   // (desnecessário: ação default)

%%
int main(){ yylex(); return 0;}

How to use it:

flex -o trunca.c trun.fl 
cc   -o trunca   trunca.c
echo "liberdade, igualdade e fraternidade" | trunca

gives what expected:

libe, igua e frat
    
17.03.2015 / 10:54