Albertong27 - 2 months ago 8
C Question

# Search a Number

How can I search for a number in a variable?

For Example:

• Input A : 12131415

Input Search : 1

Output : 1 = 4

• Input A : 12131415

Input Search : 12

Output : 12 = 1

I'll not provide a complete solution for you but here is a basic idea that you can work with.

You could convert the numbers into strings and then count the number of times you can find one string in the other.

Here are some of the basic function you can use. This should get you started.

``````int A = 12131415;
int B = 1;
int count = 0;

char strA[20];
char strb[20];

sprintf(strA, "%d", A);
sprintf(strB, "%d", B);
int lenB = strlen(strB);

char* m;
char* t = A;
m = strstr(t, strB);
if (m != NULL)
{
// Found a match
++count;
}
else
{
// No more matches
return;
}

// Move pointer
t = m + lenB;

// Now look for next match
m = strstr(t, strB);

//.... and so on....
``````

Your task is to organize the above code in a loop so that you can go through the whole string `A`.

Source (Stackoverflow)