我想拆分以下字符串:
9 0.1 10 0.2 5 1.3 400 0.4 53 0.5 6 0.6
创建一个矩阵2XN,演示一个函数,例如从A(源)到B(范围)。
9 | 10 | 5 |400 | 53 | 6
0.1| 0.2 |1.3 |0.4 |0.5 | 0.6
到目前为止我做的是:
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = (char *)malloc(length+1);
if (pointer == NULL)
{
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
for (c = 0 ; c < position -1 ; c++)
string++;
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *string;
string++;
}
*(pointer+c) = '\0';
return pointer;
}
void fillMatrix(int **functionC,int rows, int cols , char *Text){
int head=0;
int tail=0;
int index=0;
int i=0,j=0;
while(Text[index]!='\0')
{
if(Text[index]==' ')
{
head=index+1;
//printf("tail %d, head %d \n",tail,head);
printf("%s",substring(Text,tail,(head-tail)));
tail=head;
}
printf("\n");
index+=1;
}
}
fillMatrix函数应该填充functionC矩阵,因为我提到了一个开头
直到现在它只是切断了字符串。
感谢。
答案 0 :(得分:0)
一种方式
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
size_t item_count(const char *text, size_t *length){
size_t count=0, len=0;
const char *p;
bool isSpace = true;//start from not item
for(p=text; *p ;++p, ++len){
if(isspace(*p)){
isSpace = true;
} else if(isSpace){
isSpace = false;
++count;
}
}
if(length && !*length)
*length = len;
return count;
}
double **fillMatrix(int *cols, const char *Text){
size_t items, len =0;
items = item_count(Text, &len);
*cols = items / 2;
double **array = malloc(2* sizeof(double*));
array[0] = calloc(*cols, sizeof(double));
array[1] = calloc(*cols, sizeof(double));
char *token, *text = malloc(len+1);
strcpy(text, Text);
int i, j;
token = text;
for(i=0;i<*cols;++i){
for(j=0;j<2;++j){
token = strtok(token, " ");
//if(token == NULL)break;
array[j][i]=strtod(token, NULL);
token = NULL;
}
}
free(text);
return array;
}
int main(){
char *source = "9 0.1 10 0.2 5 1.3 400 0.4 53 0.5 6 0.6";
int r, c, cols;
double **array;
array = fillMatrix(&cols, source);
for(r = 0; r < 2; ++r){
for(c = 0; c < cols ; ++c){
printf(" %4g ", array[r][c]);
if(c == cols - 1){
printf("\n");
} else {
printf("|");
}
}
}
free(array[0]);
free(array[1]);
free(array);
return 0;
}