C Delete last character in string

JeongHyun picture JeongHyun · Jun 10, 2016 · Viewed 17k times · Source

I want to delete last character in string first, i use strtok function My Input is : "Hello World Yaho" I use " " as my delimeter

My expectation is this

Hell
Worl
Yah

But the actual output is this

Hello
Worl
Yaho

How can I solve this problem? I can't understand this output

this is my code

int main(int argc, char*argv[])
{
   char *string;
   char *ptr;
   string = (char*)malloc(100);

   puts("Input a String");
   fgets(string,100,stdin);

   printf("Before calling a function: %s]n", string);

   ptr = strtok(string," ");

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

   while(ptr=strtok(NULL, " "))
   {
      ptr[strlen(ptr)-1]=0;
      printf("%s\n", ptr);
   }

   return 0;
}

Answer

Niklas R. picture Niklas R. · Jun 10, 2016

This program deletes the last character of every word.

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

int main(int argc, char*argv[]){

    char *string;
    char *ptr;
    string = (char*)malloc(100);
    puts("Input a String");
    fgets(string,100,stdin);
    printf("Before calling a function: %s\n", string);
    string[strlen(string)-1]=0;
    ptr = strtok(string," ");
    printf("%s\n", ptr);
    while(ptr){
        ptr[strlen(ptr)-1]=0;
        printf("%s\n", ptr);
        ptr = strtok(0, " ");
    }
    return 0;
}

You must remember to

  1. Trim the string from trailing newline
  2. Use strtok properly

Test

Input a String
Hello World Yaho
Before calling a function: Hello World Yaho

Hello
Hell
Worl
Yah