在C中获取具有动态长度的字符串的一部分
Get part of a string with dynamic length in C
我从用户那里得到了以下字符串:
字符 *abc = "a234bc567d";
但是所有数字的长度都可以与本例中的不同(字母是常量)。
我怎样才能得到数字的每一部分? (同样,它可以是 234 或 23743 或其他......)
我尝试使用strchr和strncpy,但我需要为此分配内存(for strncpy),我希望有更好的解决方案。
谢谢。
你可以这样做:
char *abc = "a234bc567d";
char *ptr = abc; // point to start of abc
// While not at the end of the string
while (*ptr != '[=10=]')
{
// 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;
}
我从用户那里得到了以下字符串: 字符 *abc = "a234bc567d"; 但是所有数字的长度都可以与本例中的不同(字母是常量)。 我怎样才能得到数字的每一部分? (同样,它可以是 234 或 23743 或其他......)
我尝试使用strchr和strncpy,但我需要为此分配内存(for strncpy),我希望有更好的解决方案。
谢谢。
你可以这样做:
char *abc = "a234bc567d";
char *ptr = abc; // point to start of abc
// While not at the end of the string
while (*ptr != '[=10=]')
{
// 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;
}