Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut part of a string in c?

Tags:

c

string

cut

I'm trying to figure out how to cut part of a string in C. For example you have this character string "The dog died because a car hit him while it was crossing the road" how would a function go making the sentence "a car hit him while crossing the road" or "a car hit him"

How do you go about this with C's library (or/and) a custom function?

ok I don't have the main code but this is going to be the structure of this experiment

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include "display_usage.c"/*If the user enters wrong arguments it will tell them how it should be */


void cut( const char *file, int option, int first, int last );


int main(int argc, char *argv[] ) {
FILE *fp;
    char ch;
    fp = fopen("test.txt", "r"); // Open file in Read mode

    while (ch!=EOF) {
        ch = fgetc(fp); // Read a Character

        printf("%c", ch);
    }
    fclose(fp); // Close File after Reading
   return 0;
}

void cut( const char *file, int reverse, int first, int last ) {



    return;
}
like image 647
answerSeeker Avatar asked Dec 03 '13 03:12

answerSeeker


2 Answers

strncpy will only copy up to n characters. Optionally you can move a pointer around in the string, and also stick a \0 into the array to terminate it early if you have writable memory.

like image 124
woolstar Avatar answered Sep 28 '22 03:09

woolstar


The following function cuts a given range out of a char buffer. The range is identified by startng index and length. A negative length may be specified to indicate the range from the starting index to the end of the string.

/*
 *      Remove given section from string. Negative len means remove
 *      everything up to the end.
 */
int str_cut(char *str, int begin, int len)
{
    int l = strlen(str);

    if (len < 0) len = l - begin;
    if (begin + len > l) len = l - begin;
    memmove(str + begin, str + begin + len, l - len + 1);

    return len;
}

The char range is cut out by moving everything after the range including the terminating '\0' to the starting index with memmove, thereby overwriting the range. The text in the range is lost.

Note that you need to pass a char buffer whose contents can be changed. Don't pass string literals that are stored in read-only memory.

like image 45
M Oehm Avatar answered Sep 28 '22 03:09

M Oehm