簡體   English   中英

C:字符串,例如“abcde123”到int 123

[英]C: String e.g. “abcde123” to int 123

我的問題很簡單。 如果在實際整數之前有任意數量的冗余字符,C中是否有函數將字符串轉換為int?

可以指定問題以涵蓋兩個場景:1)在整數之前帶有空格的字符串:“abcde 123”2)在整數之前帶有任何非數字字符串的字符串:“abcde:123”

scanf系列函數可用於執行此操作。 所以我先說明並事后解釋:

int x;
scanf("%*[^0123456789+-]%d", &x);

第一個格式說明符是[] 它指定了scanf應該接受的一系列字符。 領先^否定了這一點,所以比其他家庭任何被接受指定器。 最后, *用於抑制實際輸入,因此在掃描輸入流的模式時,不會嘗試將其分配給任何內容。

您可以使用ctype.h isalphaisdigit來查找第一個數字,然后使用atoiatolatollstrolstroll轉換為int ,例如:

#include <ctype.h>
#include <stdlib.h>

int main(void) {
  char str[] = "abcde123";

  char *p = str;
  while (isalpha(*p)) ++p;
  int i = atoi(p);
}

請注意,“如果[ atoi / atol / atoll ]的轉換值超出相應返回類型的范圍,則返回值未定義。” 來源 )。

您可以使用sscanf() ,也可以使用strtoll()

//char string1[] = "abcde:123";
    char string[] = "ab23cde:123";
    int values[4]; // specify the number of integers expected to be extracted
    int i = 0;
    char *pend = string;
    while (*pend) {
        if (isnumber(*pend)) {
            values[i++] = (int) strtoll(pend, &pend, 10);
        } else {
            pend++;
        }
    }

//you can use a forloop to go through the values if more integers are expected

        printf("%d \n",values[0]);
        printf("%d \n",values[1]);

23
123

基本上,字符串中整數的位置無關緊要,它將提取所有這些整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM