Quantcast
Channel: Maris Labs
Viewing all articles
Browse latest Browse all 19

Concaving Strings in C

$
0
0

Ever want to shorten a string if it’s too long but do not want to cut off the beginning or end of it?

Concave the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <string.h>

#define STR_SIZE_LIMIT 25

char *str_concave(const char *str, char *buffer, int size_limit) {
    int str_size = (int)strlen(str);
   
    if (str_size <= size_limit) { strcpy(buffer, str); return buffer; }
   
    int half = (int)size_limit / 2;
    int i = half;
    int left_over = size_limit % 2;
    int apposition_size = 3;
    int end = half - apposition_size + left_over;
   
    memcpy(buffer, str, half);
    memcpy(buffer + half, "...", apposition_size); /* add the apposition */           i += apposition_size;
    memcpy(buffer + i, str + ((str_size - half) + apposition_size - left_over), end); i += end;
    buffer[i] = '\0';

    return buffer;
}

int main(void) {
    char old_string[64] = "The black fox jumped over the whatever, I forgot the phrase!";
    char new_string[STR_SIZE_LIMIT];
   
    str_concave(old_string, new_string, STR_SIZE_LIMIT);

    printf("\n%s\n", old_string);
    printf("%s\n", new_string);

    printf("\nstrlen(old_string) = %d\n", (int)strlen(old_string));
    printf("strlen(new_string) = %d\n", (int)strlen(new_string));
   
    return 0;
}

Output:

The black fox jumped over the whatever, I forgot the phrase!
The black fo…he phrase!

strlen(old_string) = 60
strlen(new_string) = 25


Viewing all articles
Browse latest Browse all 19

Trending Articles