-5

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

Please Help Me. Thank You.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
rtr0_id
  • 1
  • 3
  • 3
    First of all, C and C++ are different languages. You can't have both. Second, this is probably a homework question and you will find your answer quicker with your favorite search engine than it takes to write this question here. Please read the help section about how and what to ask here. – Sami Kuhmonen Oct 02 '16 at 05:31
  • 1
    We'll help you fix a genuine attempt to solve the problem. We won't usually write the code for you. Show us your best effort. Unless there are rules you haven't told us about, you should read strings and do string analysis, not numerical analysis. – Jonathan Leffler Oct 02 '16 at 05:34
  • @Sami Kuhmonen Yes you right , but please note that this is not a homework but this is is my friend's question. – rtr0_id Oct 02 '16 at 05:37
  • 2
    I don't think the proposed duplicate is very close to being a duplicate. The question is notable for have a -5 accepted answer, but that's not why it is not a duplicate, though. This question is about counting the occurrences of a (digit) string inside another (digit) string. That question is about identifying the digits present in a … number, but it could be a string. – Jonathan Leffler Oct 02 '16 at 05:37
  • 3
    @Albertong27: pull the other one! And it is probably his (or her) homework question, and they could perfectly well ask for themselves. That's not a good excuse. – Jonathan Leffler Oct 02 '16 at 05:38
  • JFTR: the 'proposed' duplicate was [C++ get each digit in int](http://stackoverflow.com/questions/4615046/c-get-each-digit-in-int). I reopened because the duplicate was not good. That is not to indicate that the question is good; it isn't — it should be closed because there's no effort put into showing the attempted code, etc. – Jonathan Leffler Oct 02 '16 at 05:53

1 Answers1

0

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.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63