Created
January 15, 2017 03:54
-
-
Save hecerinc/1905fa922e931d78319b0e898a14097c to your computer and use it in GitHub Desktop.
Split in C example with variable length string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <cs50.h> | |
#include <stdlib.h> | |
int main(void){ | |
string s = get_string(); // replace this for char * and read to it in an normal way | |
int n = strlen(s), number_words = 0; | |
char *c; | |
//c = malloc((5+1)*sizeof *c); | |
// strncpy(c, s, 5); | |
// c[5] = '\0'; | |
// printf("%s\n", c); | |
// free(c); | |
for(int i = 0; i < n; i++){ | |
if(s[i] == ' ') | |
number_words++; | |
} | |
number_words++; | |
// Split | |
int j = 0, k = 0; | |
char ** words = (char **) malloc(number_words * sizeof c); | |
char *x; | |
for(int i = 0; i < n; i++){ | |
if(s[i] == ' '){ | |
x = malloc((i-k+1) * sizeof *c); | |
strncpy(x, s+k, (i-k)); | |
x[i-k] = '\0'; | |
//printf("%s\n", x); | |
words[j] = x; | |
j++; | |
k = i+1; | |
} | |
} | |
k--; | |
x = malloc((n-k) * sizeof *c); | |
strncpy(x, s+k+1, (n-k-1)); | |
x[n-k-1] = '\0'; | |
//printf("%s\n", x); | |
words[j] = x; | |
j++; | |
for(int i = 0; i < number_words; i++){ | |
printf("%s\n", words[i]); | |
free(words[i]); | |
} | |
free(words); | |
free(c); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment