How to get substring in C

后端 未结 4 708
北海茫月
北海茫月 2020-12-09 11:52

I have a string, let\'s say \"THESTRINGHASNOSPACES\".

I need something that gets a substring of 4 characters from the string. In the first call, I should get \"THES\

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 12:14

    If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

    strncpy(sub1, baseString, 4);
    strncpy(sub1, baseString+4, 4);
    strncpy(sub1, baseString+8, 4);
    

    or

    for(int i=0; i<4; i++)
        sub1[i] = baseString[i];
    sub1[4] = 0;
    for(int i=0; i<4; i++)
        sub2[i] = baseString[i+4];
    sub2[4] = 0;
    for(int i=0; i<4; i++)
        sub3[i] = baseString[i+8];
    sub3[4] = 0;
    

    Prefer strncpy if possible.

提交回复
热议问题