How to get substring in C

后端 未结 4 683
北海茫月
北海茫月 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:07
    char originalString[] = "THESTRINGHASNOSPACES";
    
        char aux[5];
        int j=0;
        for(int i=0;i<strlen(originalString);i++){
            aux[j] = originalString[i];
            if(j==3){
                aux[j+1]='\0'; 
                printf("%s\n",aux);
                j=0;
            }else{
                j++;
            }
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 12:14

    If you just want to print the substrings ...

    char s[] = "THESTRINGHASNOSPACES";
    size_t i, slen = strlen(s);
    for (i = 0; i < slen; i += 4) {
      printf("%.4s\n", s + i);
    }
    
    0 讨论(0)
  • 2020-12-09 12:18
    #include <stdio.h>
    #include <string.h>
    
    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题