今天有個來我們公司面試,要做機試題目,本來想讓我幫忙看看來,結果我去看題目,發現寫的時候麻煩點
最煩字符串的處理啦
題目是這樣的:(1)輸入一行字符串,格式是4 12 234 45 66,第一個數字是後邊數字的個數
(2)輸出類似這種形式“this char[]="0x34,0x22,0x44,0x77"
和同事商量後,同事給的思路是寫一個切割函數,然後轉化即可。我想了想,還有很多異常判斷啊!
具體代碼如下(未調試,明個測一把,肯定很多錯誤)
//切割函數
int split(const char *str, char **dest)
{
if(str[0] == '\0')
{
return -1;
}
int i = 0;
int num = 0;
int j = 0;
while(str[i] != '\0')
{
if(str[i] >= '0' && str[i] <= '9')
{
i++;
num++;
}
else if(str[i] == '')
{
memcpy(*(dest+j),str,num);
num = 0;
j++;
continue;
}
else
{
return -1;
}
}
**(dest+j+1)='\0'
return j;
}
//轉化函數
void change(const char** src,int* temp, int j)
{
int temp[j+1];
for(int i = 0 ; i < j; i++)
{
temp[i] = atoi(*src+i);
}
temp[j+1] = '\0';
}
//main函數
void main()
{
char * str;
//輸入一行字符串,測試
printf("輸入一行字符串:");
scanf("%s",&str);
//切割字符串
int i = 0;
char **dest;
int *temp;
i = split(str, *dest);
change(*dest,temp,i);
//十六進制printf
}