如何修剪并将字符串数组传递给函数?

时间:2011-10-22 21:10:59

标签: c string

如何将字符串修剪为N个字符的片段,然后将它们作为字符串数组传递给函数?

这是我程序中转换二进制< - > hex的部分内容。

我尝试用字符串做同样的事情,但它不起作用。

#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];
}

2 个答案:

答案 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;
    }
}

答案 1 :(得分:0)

你是否必须null终止字符串,你对这个使用的内存有限制吗?你需要正确分配内存吗?更多信息将是有用的

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循环结束时终止。这不是完全漂亮的代码,但它应该完成这项工作。关于其他要求的更多信息可能是好的。