print specific char of a string

I'm working w/ strings and I was wondering how would I go about printing on the last 2 letters and the middle two letters of "bobby"

printf("%s\n", mid(LN, 2,2)); //should print bb
printf("%s\n", right(LN, 2)); //should print by

any help is much appreciated, still learning strings.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  //
//  main.cpp

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

char* left(char* str, int len) {
    char* ret;
    ret = (char*)(malloc(sizeof(char)* (len + 1)));
    strncpy(ret, str, len);
    ret[len] = '\0';
    return ret;
}
char* mid (char* str, int start, int len) {
    char* ret;
    ret = (char*)(malloc(sizeof(char)* (len + 1)));
    strncpy(ret, str, len);
    ret[len] = '\0';
    return ret;
}
char* right (char* str, int len) {
    char* ret;
    ret = (char*)(malloc(sizeof(char)* (len + 1)));
    strncpy(ret, str, len);
    ret[len] = '\0';
    return ret;
}


bool equal(char* str1, char* str2) {
    bool ret = true;
    long length;
    int i = 0;
    
    if (strlen(str1) > strlen(str2))
        length = strlen(str1);
    else
        length = strlen(str2);
    
    while (ret && i < length) {
        if ((str1[i] & 223) != (str2[i] & 223))
            ret = false;
        i++;
    }
    return ret;
}





int main(int argc, const char * argv[]) {
    char FN[4], LN[20];
    strcpy(FN, "bobby");
    strcpy(LN, "bobby");
    
    if (equal(FN, LN))
        printf("They are the same\n");
    else
        printf("They are different\n");
    
    printf("%s\n", left(LN, 2));
    printf("%s\n", mid(LN, 2,2));
    printf("%s\n", right(LN, 2));

    
    return 0;
}
Last edited on
if you are using c++ then you should go for std::string . this is more flexible
Topic archived. No new replies allowed.