2013-12-18 32 views
1

我想要分割以下字符串:
創建自定義矩陣從字符串

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矩陣正如我所提到的一個開始。
直到現在它只是切斷了繩子。

  1. 還有另一種方法可以做到這一點?那更好?
  2. 我想得到一些建議,我可以如何實現這一點。


謝謝。

+0

不完全一樣,但可以給你的想法。 http://rosettacode.org/wiki/Zig-zag_matrix –

+0

函數C矩陣的類型爲int? – BLUEPIXY

+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; 
} 
+0

我收到了很多錯誤。 –

+0

@OfirAttia如果您使用MSVC,請嘗試在變量聲明塊的開頭。而你使用int而不是bool。 – BLUEPIXY

+0

我可以在clang和gcc中無誤地運行。 – BLUEPIXY