下面的代码段提取字符串str []的前两个数字字符并将它们放入i1作为它们表示的十进制值并提取字符串str的最后两个数字字符并将它们作为十进制值放入i2中它们表示;这样底部的打印语句将在屏幕上打印12和67.
#include<stdio.h>
main(){
char str[]="1234567";
int i1, i2;
//write code here
printf("%d %d\n, i1, i2);
}
我很想做什么。我假设我想使用strcat(i1, i2)
,但是当我将其打印出来时,我没有收到12
和67
。
这是什么解决方案?谢谢你的帮助!
答案 0 :(得分:2)
数字字符代码保证在一系列中
(从0
到9
。例如'0' + 1
成为'1'
),
因此,您可以通过减去'0'
将它们转换为数字
此外,由于字符串的结尾有NUL字符('\0'
或简称0
),所以
您可以通过查找找到最后两个字母。
(例如str[index] == '\0'
或str[index] == 0
或简称!str[index]
)
所以总的来说,它可以写成如下的一个例子。
#include <stdio.h>
int main(void){
char str[]="1234567";
int i1, i2;
#define dc2i(dc) ( dc - '0' ) //convert one digit character to int
#define d22i( s) ( 10*dc2i(*s) + dc2i(s[1]) ) //two digit to int
{
const char *i1p = str, *i2p;
//Is it necessary to check if the whole is composed only of numeric characters?
if(!*str || !str[1]){//Is it length of 2 or more? (Do you need a length of 4 or more?)
fprintf(stderr, "'%s' is too short string.", str);
return 1;
}
for(const char *p = str; *p && p[1]; ++p)
i2p = p;//save last pointer
i1 = d22i(i1p);
i2 = d22i(i2p);
}
printf("%d %d\n", i1, i2);
}
答案 1 :(得分:0)
如果你的字符串的长度等于或大于4,并且只包含数字,那么这段代码应该可以解决问题。你的假设没有错,你的问题确实可以通过strcat()函数来解决,但是它稍微长一些,也有点复杂。
#include <stdio.h>
#include <string.h>
main(){
char str[]="1234567";
int i1, i2;
i1 = (str[0] - '0') * 10 + (str[1] - '0');
int length = strlen(str);
i2 = (str[length - 2] - '0') * 10 + (str[length - 1] - '0');
printf("%d %d\n", i1, i2);
return 0;
}
答案 2 :(得分:0)
虽然您可以通过手动从字符转换为int直接转换为i1
和i2
,但stdlib.h
提供了strto..
系列函数来为您执行转换同时提供错误检查。 (例如strtol
,strtoul
等。)。虽然转换本身相当简单,但请始终检查标准库函数是否已经完成了您尝试执行的操作。如果存在的话,它可能会有数十年的使用和验证,并且可能比你重新发明的要好一些。
采用这种方式,您的任务变得简单地创建包含所需数字的str
的子字符串,然后将子字符串传递给strtol
以转换为int
(同时strtol
返回long
值,在这种情况下给定str
的明确定义,没有超出int
的存储容量的可能性,并且不可能遇到字符串中除数字之外的其他内容)因此,对errno
进行简单检查即可确保从str
转换为long
并转换为int
将解决类型差异。
将这些部分放在一起,你可以做类似以下的事情:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
enum { NCHR = 2, NOFF = 5 }; /* constants, no. chars, i2 offset */
int main (void) {
char str[]="1234567",
buf1[NCHR + 1] = "", /* buffer to hold substrings */
buf2[NCHR + 1] = ""; /* initialized to provide termination */
int i1 = 0,
i2 = 0;
for (int i = 0; i < NCHR; i++) { /* fill substrings */
buf1[i] = str[i]; /* buf1[] = "12" */
buf2[i] = str[i + NOFF]; /* buf2[] = "67" */
}
errno = 0; /* initialize errno */
i1 = (int)strtol (buf1, NULL, 10); /* perform converstions */
i2 = (int)strtol (buf2, NULL, 10);
if (errno) { /* validate errno remains 0 or handle error */
fprintf (stderr, "error: failed converstion for i1 or l2.\n");
return 1;
}
printf ("i1 = %d\ni2 = %d\n", i1, i2);
return 0;
}
注意: buf1
和buf2
必须以 nul-terminatedating 字符'\0'
结尾(或等效{{1} }})。通过在声明时将每个字符初始化为0
来保证终止 - 并且在代码中使用期间不覆盖最终的0
。
示例使用/输出
0
无论哪种方式,你选择接近问题都没关系。只要您的代码有效,就没有任何一种方法比其他方式更正确(您可以在学习C语言时担心优化和调整指令数量)。在所有答案中查看一切,让任何作者知道您是否有疑问。