2011-10-22 102 views
-2

如何將字符串修剪成N個字符的碎片,然後將它們作爲字符串數組傳遞給函數?如何修剪並傳遞一個字符串數組到一個函數中?

這在我的程序的一部分,轉換二進制< - >十六進制。

我試着用字符串做同樣的事情,但沒有奏效。

#include <math.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <String.h> 

#define MAXDIGITS 8 // 8bits 


int main() 
{ 
    int y; 

    printf("Binary-Hex convertor\n"); 
    printf("Enter the Binary value : "); 
    scanf("%d", &y); 

    int i = MAXDIGITS - 1; 
    int array[MAXDIGITS]; 

    while(y > 0) 
    { 
     array[i--] = y % 10; 
     y /= 10; 
    } 

    printf("%s", "-----------------\n"); 
    printf("%s", "HEX:"); 

    int x = array[0]; 
    int x1 = array[1]; 
    int x2 = array[2]; 
    int x3 = array[3]; 
    int x4 = array[4]; 
    int x5 = array[5]; 
    int x6 = array[6]; 
    int x7 = array[7]; 

    char buffer[50]; 
    char buffer2[50]; 
    char buffer3[50]; 
} 
+0

猜猜這是功課... – BlackBear

+0

太聰明瞭!這不是作業。即使這是作業,爲什麼你不會與其他人分享知識? – Faisal

+0

你能告訴我們你試過了什麼嗎? –

回答

1

如果它只是二進制字符串中的詛咒,那麼這是很容易....

char *input_string = "1001010101001010"; 
int count = 0; 
int value = 0; 

while (*input_string != '\0') 
{ 
    // Might be worth checking for only 0 and 1 in input string 
    value <<= 1; 
    value |= (int)((*input_string--) - '0'); 

    if (++count == 8 || *input_string == '\0') 
    { 
     // USE value to print etc, if you want to display use 
     // the following else you could store this in an array etc. 
     printf("%x ", value); 
     count = 0; 
     value = 0; 
    } 
} 
0

你一定要空終止字符串,你對這個內存使用的限制。你需要正確分配內存等嗎?多一點信息將是有用的

const char *input_string = "HELLO THIS IS SOME INPUT STRING"; 
int N = 4; // The number to split on 

// Work out how many strings we will end up in 
int number_of_strings = (strlen(input_string) + (N - 1))/N; 

// ALlow for an extra string if you want to null terminate the list 
int memory_needed = ((number_of_strings + 1) * sizeof(char *)) + (number_of_strings * (N + 1)); 
char *buffer = malloc(memory_needed); 
char **pointers = (char **)buffer; 
char *string_start = (buffer + ((number_of_strings + 1) * sizeof(char *)); 
int count = 0; 

while (*input_string != '\0') 
{ 
    // Fresh string 
    if (count == 0) 
    { 
     *pointers++ = string_start; 
     *pointers = NULL; // Lazy null terminate 
    } 

    // Copy a character 
    *string_start++ = *input_string++; 
    *string_start = '\0'; // Again lazy terminat  

    count++; 

    if (count == N) 
    { 
     count = 0; 
     string_start++; // Move past the null terminated string 
    } 
} 

然後,您可以通過(char **)緩衝區;到一個例程。我實際上沒有嘗試過這種方式,因爲我一直懶於終止字符串。您可以在計數運行結束和while循環結束時結束。這不完全相當的代碼,但它應該做的工作。有關其他要求的更多信息可能會更好。

相關問題