Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Delete last character in string

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;
}
like image 436
JeongHyun Avatar asked Jun 10 '16 06:06

JeongHyun


2 Answers

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
like image 68
Niklas Rosencrantz Avatar answered Sep 21 '22 07:09

Niklas Rosencrantz


Your problem is best solved by splitting it in 2 phases: parsing the phrase into words on one hand, with strtok if you wish, and printing the words with their last character omitted in a separate function:

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

static void print_truncated_word(const char *ptr) {
    int len = strlen(ptr);
    if (len > 0) len -= 1;
    printf("%.*s", len, ptr);
}

int main(int argc, char*argv[]) {
    char buf[128];
    char *ptr;

    puts("Input a string: ");
    if (fgets(buf, sizeof buf, stdin) == NULL) {
        /* premature end of file */
        exit(1);
    }
    printf("Before calling a function: %s\n", string);

    ptr = strtok(string, " \n");
    while (ptr) {
        print_truncated_word(ptr);
        ptr = strtok(NULL, " \n");
    }
    return 0;
}

Note that the print_truncated_word function does not modify the buffer. Side effects on input arguments should be avoided, unless they are the explicit goal of the function. strtok is ill behaved to this regard, among other shortcomings such as its hidden state that prevents nested use.

like image 36
chqrlie Avatar answered Sep 22 '22 07:09

chqrlie