我有一些格式为“10.214.239”的字符串,我想将其转换为整数。一些字符串只有几千个,因此只包含1个点,但有些是数百万个,因此包含2个点。有没有一种简单的方法可以解决这个问题?
答案 0 :(得分:6)
int i, len;
int result=0;
len = strlen(num);
for(i=0; i<len; i++){
if(num[i] >= '0' && num[i] <= '9' )
result=(result*10)+(num[i]-'0')
}
printf("%d", result);
答案 1 :(得分:4)
你大概需要这个:
int main()
{
const char num[] = "12.345.66";
char buffer[100];
// copy string to buffer skipping dots
char c;
int j = 0;
for (int i = 0; c = num[i]; i++)
{
if (c != '.')
buffer[j++] = c;
}
// put the NUL strig terminator
buffer[j] = 0;
// convert string stripped of dots to long
long number = strtol(buffer, NULL, 10);
}
免责声明:这是非错误检查,快速编写的代码不应该像现在这样使用,但它应该让您知道您需要做什么。
答案 2 :(得分:2)
简单的解决方案:
int i,ans=0;
for(i=0;num[i];i++)
if(num[i]!='.') ans=ans*10+num[i]-'0';
printf("%d",ans);
答案 3 :(得分:0)
只需浏览每个字符,然后使用<ctype.h>
中的isdigit()
来确定字符是否为数字。像这样的东西会起作用:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
const char *test = "10.214.239";
const char neg = '-';
long number = 0;
for (size_t i = 0; test[i] != '\0'; i++) {
if (isdigit(test[i])) {
number *= 10;
number += test[i] - '0';
}
}
/* if first character is a dash, make sure the converted number is negative */
if (test[0] == neg) {
number *= -1;
}
printf("number = %ld\n", number);
return 0;
}
答案 4 :(得分:0)
到目前为止,与所有其他答案不同的方法是利用旨在处理操作/句柄字符串的标准库函数。例如,可以使用sscanf
:
#include <stdio.h>
int main(void) {
const char *test = "10.214.239";
int vals[3] = {0, 0, 0};
const int n = sscanf(test, "%i.%i.%i", &vals[0], &vals[1], &vals[2]);
const int exponent = n < sizeof(vals)/sizeof(int) ? 1: 1E3;
long number = vals[0]*1E3*exponent + vals[1]*exponent + vals[2]);
printf("%ld\n", number);
return 0;
}
或者,您也可以使用strtok
拆分字符串,使用atol
将每个子字符串转换为数字:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *test = "10.214.239";
char *tok = test;
const int exponent = 1e3;
long ans = 0;
while ((tok = strtok(tok, ".")) != NULL) {
ans = ans*exponent + atol(tok);
tok = NULL;
}
printf("%ld\n", ans);
return 0;
}