Split array by space into words
I got this code right here, which works.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "Hello how are you";
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
but instead of char str1[100]
I want to use an array of sentenceschar str1[2][100]
Meaning
char str1[2][100] = {"Hello how are you","I'm good, thanks"}
And these two sentences (or more) I want to be separated in separate words
char str1[100] = {"Hello","how","are","you"};
Actually, this is from a project for school, in which from a file, i have to store each sentence ended by '.'
If there is another way to store each sentece directly as words instead of sentences, it would be great help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
void yodificacio(char* arr[], int index[], int n)
{
char* temp[n];
// arr[i] should be present at index[i] index
for (int i=0; i<n; i++){
temp[index[i]] = arr[i];
}
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
{
arr[i] = temp[i];
index[i] = i;
}
}
int main()
{
int i = 0;
char *arr[] = {"Hey","there","how","are","you","all","today","idk"}; **Here I want the input to be char str1[2][100] = {"Hello how are you", "Im good thanks}, instead of char arr[] ...**
int index[] = {0,2,1,4,5,3,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
yodificacio(arr, index, n);
printf("Reordered array is: \n");
for (int i=0; i<n; i++)
printf ("%s ", arr[i]);
return 0;
return 0;
}
Solution 1:
Add an outer loop to process each sentence in the array.
int main()
{
char str1[2][100] = {"Hello how are you","I'm good, thanks"} ;
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
j=0; ctr=0;
for (int k = 0; k < sizeof(str1) / sizeof(str1[0]); k++) {
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[k][i]==' '|| str1[k][i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[k][i];
j++;
}
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}