Problem accessing array element

Asked

Viewed 199 times

5

I have a problem in the function below that truncates all words to have at most N characters.

For example: if the string "freedom, equality and fraternity" means the invocation of truncW(t,4) should give "libe igua 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);
}

The output gives only : "libe"

I wonder how I do to go through the entire list and take out at most n characters of each word . What is missing in the code to allow this?

4 answers

6


Your biggest problem is here:

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

That means you’ll only walk through the first ones n string characters, not each word.

I think the best way to do that is to have an accountant count how many letters in a word you’ve ever seen, and make sure you get it every time 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;
}

5

You have to continue going 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 of 0 to n, play 0 at 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 taken from words, not the spaces between them (i.e. the output will be libeiguaefrat). If you also want to print the spaces, see the response of Victor Stafusa.

4

You weren’t sweeping the whole string and I was still 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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

  • if (isspace(t[i]) > 0) /* ... */; ??? There is no impediment to the isspace() return a negative number to indicate true.

3

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;}

Method of use:

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

gives the expected:

libe, igua e frat

Browser other questions tagged

You are not signed in. Login or sign up in order to post.