Skip to content

Instantly share code, notes, and snippets.

@hecerinc
Created January 15, 2017 03:54
Show Gist options
  • Save hecerinc/1905fa922e931d78319b0e898a14097c to your computer and use it in GitHub Desktop.
Save hecerinc/1905fa922e931d78319b0e898a14097c to your computer and use it in GitHub Desktop.
Split in C example with variable length string
#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