[英]Get part of a string with dynamic length in C
我從用戶那里得到了以下字符串:char * abc =“ a234bc567d”; 但是所有數字的長度都可以與此示例不同(字母為常數)。 如何獲得數字的每個部分? (同樣,它可以是234或23743或其他。)
我嘗試使用strchr和strncpy,但是我需要為此分配內存(用於strncpy),我希望有更好的解決方案。
謝謝。
您可以執行以下操作:
char *abc = "a234bc567d";
char *ptr = abc; // point to start of abc
// While not at the end of the string
while (*ptr != '\0')
{
// If position is the start of a number
if (isdigit(*ptr))
{
// Get value (assuming base 10), store end position of number in ptr
int value = strtol(ptr, &ptr, 10);
printf("Found value %d\n", value);
}
else
{
ptr++; // Increase pointer
}
}
如果我理解您的問題,則您正在嘗試提取包含數字的用戶輸入部分...並且數字序列可以是可變的...但字母是固定的,即a或b或c或d。 正確...? 以下程序可能會為您提供幫助。 我嘗試將其用於字符串“ a234bc567d”,“ a23743bc567d”和“ a23743bc5672344d”。 作品...
int main()
{
char *sUser = "a234bc567d";
//char *sUser = "a23743bc567d";
//char *sUser = "a23743bc5672344d";
int iLen = strlen(sUser);
char *sInput = (char *)malloc((iLen+1) * sizeof(char));
strcpy(sInput, sUser);
char *sSeparator = "abcd";
char *pToken = strtok(sInput, sSeparator);
while(1)
{
if(pToken == NULL)
break;
printf("Token = %s\n", pToken);
pToken = strtok(NULL, sSeparator);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.