How to get a substring in C

I have a string, say, "THESTRINGHASNOSPACES" I need something that gets a substring of 4 characters from a string. In the first call I have to get "THES" in the second, I have to get "TRIN". in the third I have to get "GHAS", how can I do this in C?

+8
c
source share
4 answers

If the task is only to copy 4 characters, try using loops. If it will be more advanced and you ask 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.

+8
source share
 #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); } } 
+4
source share

If you just want to print substrings ...

 char s[] = "THESTRINGHASNOSPACES"; size_t i, slen = strlen(s); for (i = 0; i < slen; i += 4) { printf("%.4s\n", s + i); } 
0
source share
 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
source share

All Articles