简体   繁体   English

atoi从定义的索引转换为字符串到字符串

[英]string to char conversion by atoi from a defined index

Let's say I have char x[3] = "123"; 假设我有char x[3] = "123"; and I would like to convert only index 1 and index2 " 23 " of the char array, can I do it by atoi ? 我想只转换char数组的索引1和index2“ 23 ”,我可以通过atoi来做吗?

I know I can do it by char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z); 我知道我可以通过char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z);来做到这一点char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z); char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z); but it is not what I am asking for. 但这不是我要求的。

You can do this with 你可以这样做

char x[4];
int i;

strcpy(x, "123");
i = atoi(x + 1);

Because x is a pointer to char, x + 1 is a pointer to the next char. 因为x是指向char的指针,所以x + 1是指向下一个char的指针。 If you try to print with 如果您尝试打印

printf("%s", x + 1);

You'l get 23 as the output. 你得到23作为输出。

Note though that you need to declare the length of the char array to be one more than the number of characters in it - to accommodate the ending \\0 . 请注意,您需要声明char数组的长度比其中的字符数多一个 - 以容纳结尾\\0

If you wish to convert the first digit, then the remaining part of the string, you can do: 如果您希望转换第一个数字,然后转换字符串的剩余部分,您可以执行以下操作:

char x[] = "123";

int first = x[0]-'0';
int rest  = atoi(&x[1]);

printf("Answers are %d and %d\n", first, rest);

Result: 结果:

Answers are 1 and 23

Yes, you can convert such a "suffix" string by giving atoi() a pointer to the first character where you want conversion to start: 是的,您可以通过给atoi()指向要转换开始的第一个字符的指针来转换这样的“后缀”字符串:

const int i = atoi(x + 1);

Note that this only works for a suffix, since it will always read up to the first '\\0' termiator character. 请注意,这仅适用于后缀,因为它将始终读取第一个'\\0'终结器字符。

Also note, as pointed out in a question comment, that this assumes there is a terminator, which your code won't have. 另外请注意,在一个问题的评论中指出,这一假设一个终结者,你的代码将不会有。

You must have: 你必须有:

char x[4] = "123";

or just 要不就

char x[] = "123";

or 要么

const char *x = "123";

To get the terminator to fit. 让终结器适合。 If you don't have a terminated array, it's not a string, and passing a pointer to any part of it to atoi() is not valid. 如果你没有终止数组,它不是一个字符串,并且将指向它的任何部分的指针传递给atoi()是无效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM