How to get substring in C

后端 未结 4 706
北海茫月
北海茫月 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 12:18

    #include 
    #include 
    
    int main() {
        char src[] = "SexDrugsRocknroll";
        char dest[5] = { 0 }; // 4 chars + terminator */
        int len = strlen(src);
        int i = 0;
    
        while (i*4 < len) {
            strncpy(dest, src+(i*4), 4);
            i++;
    
            printf("loop %d : %s\n", i, dest);
        }
    }
    

提交回复
热议问题