hi all im stuck to my assignment

1. i want to know how to use function search in order i can search each character in a string then count the number of it.

for example: given : home alone
the output will be :

the string has 9 characters including the white space.

if i want to search character a in the string
the output will be

1 a found in the string home alone.

if i want to search y in the string the output will be

no y is found in the string home alone

so far this is the code that i made:

#include<stdio.h>
#include<string.h>

void searchCount(char*TEXT, char z);

int main(){
int string_size;
char a;

char name[]="HAPPY BIRTHDAY";
name[strlen(name)-1]='\0';
printf("find a character>>");
scanf("%c", &a);

searchCount(name,);  //this part i have to calling searchCount function but i have no idea which argument i have to pass in

printf("The string has %d characters including white space.",i);

return 0;
}

void searchCount(char *TEXT, char z){

//no idea to put in//

return count;
}

i think i have to use switch but serious i dont understand how to mix it with pointer,pls any idea?

Recommended Answers

All 27 Replies

OK, let's do one thing at a time.

First up, why is line #11 there? Secondly, does your existing code actually print the length of the string? Why not?

ok i change my code a bit to this

#include<stdio.h>
#include<string.h>

int searchCount(char *TEXT, char z);

int main()
{
        int total;
        char a;
        char *TEXT="DATA STRUCTURE";
        printf("find a character>>");
        scanf("%c",&a);
        total=searchCount(TEXT,a);
        printf("\n The string '%s' have %d character '%c'.",TEXT,total,a);
return 0;
}

int searchCount(char *TEXT, char z)
{
        int coun
  int count=0;
        int i;
        for(i=0;i<strlen(TEXT);++i)
        {
               if(TEXT[i]==z)
               count++; 
        }
        return count;
}
 void searchCount(char *TEXT, char z){
int count=0;
int i;

for(i=0;i<strlen(TEXT);i++)
{
if(TEXT[i]==z)
count++
}

//i put printf to get the output here

printf("the string '%s' have %d character",TEXT,i);
}

but now i am stuck :/

Line 11 overwrites the newline char from the char name[].

Your search function has two types of searches:

1) for a specific char, and
2) for general info on the entire string.

So how about passing a '0' (zero) char, for a general, non-specific search, and anything else could be the specific char to be searched for.

So your search() declaration could be:
void search(char *name, char target)

Where target is what you're looking for, unless it's a '0' char.

The search() function will need the name of the array to be searched - "name", in your program.

and lastly, search() needs to know the specific char it is searching for, if the search is for a specific char.

C has a built in searcher for a char in a str, called strchr(). Part of the string.h file, which you'll need to include.

It's also very easy to "roll your own" by using a for loop, and "walking" the char's in the array, and counting the data you need, as you go, and printing it when the for loop is over.

Either way, up to you.

You should keep the void search(), and delete the int search(). Just add some logic into the search() function you already have.

Removing the newline was a good idea. I'd keep that old line #11.

How about printing up a prompt like this:

"Enter a char to search for, or 0 for general string information: "

then
scanf() same as now.

Then, in search()
if(charTheyEnter == '0')
get strlen();
get any other info you need for general search and print it
}
else {
//code in here for specific char searching
}

Line 11 overwrites the newline char from the char name[].

I was asking the OP, and working around to getting them to work out that they needed to store the string length in a var (which could be used both there and in their output). Never mind :icon_rolleyes:

Unfortunately, he took it to mean remove it, so he did. ;)

Didn't mean to step on your post. Go ahead and finish him off, RB.

Unfortunately, he took it to mean remove it, so he did. ;)

Didn't mean to step on your post. Go ahead and finish him off, RB.

Sorry, didn't mean to sound antsy -- having grief with my daughter this morning.

hosam2k, post up what you've actually got, please, and we'll take it from there. The code you stuck up last won't compile, as searchCount() is defined twice; let's make sure we're both talking about the same code ;-)

#include<stdio.h>
     #include<string.h>
   
      void searchCount(char *TEXT, char z);
      int count(char*DATA, char b);

      int main(){
      int total;
      char a;
      char *TEXT[name];
      printf("enter a string:");
      fgets(TEXT,name.stdin);
      printf("find a character>>");      
      scanf("%c",&a);
      searchCount(TEXT,a);
      total=count(DATA,a);
      printf("%d found in the string %s", total, DATA);
      return 0;
      }

      void searchCount(char *TEXT, char z)
      {
      int count=0;
      int i;
      for(i=0;i<strlen(TEXT);++i)
      {
      if(TEXT[i]==z)
      count++;}
      printf("The string has %d character including white space.\n",TEXT,i);
      }
  
      //in here i tried to implement another function calls for counting the occurence of specified character
      int count(char *DATA, char b){
      int total=0;
      int j;
      for(j=0;j<strlen(DATA);j++){
      if(*DATA[j]==b)
      total=total+j;}
      }

can u pls tell me where i the wrong part?and if u dont mind explain to me how this program actually work esp for counting character? coz i still mixed up between array and pointer,,thank u so much

Let's fix bits from the top down.

In main(), you've got

char *TEXT[name];

To make things simple, let's change that. Add

#define STRLEN 80

after

#include<string.h>

and alter the line where you declare TEXT to be

char TEXT[STRLEN];

This will allocate enough space in TEXT for 80 characters; including any terminating characters.

Now we've got some space set aside for the input string, let's read it in. Your line

fgets(TEXT,name.stdin);

isn't correct. Given that we've defined STRLEN as the amount of space for your string, how should your fgets() call read?

fgets(TEXT,name.stdin);

i still don't get it with this one u mean i shouldnt write this?

i use fgets to gets the input from user right?

i still dont get it with this one u mean i shouldnt write this?

i use fgets to gets the input from user right?

Yep, you do, but you are not using it right. What you need (if you've made the other changes I suggested) is:

fgets(TEXT, STRLEN, stdin);

Note the three parameters, not two.

Let's quickly deal with the other issues in main(), so we can get to the bit you are really interested in -- the counting.

You ought to be specifying what parameters main() is accepting. As you don't really care (you are not using them), let's specify void:

int main(void)

Next, you have the line

total=count(DATA,a);

which attempts to pass DATA to your count() function. But the variable DATA is never declared. What you are actually trying to do is pass your TEXT variable into count(), so the line should read:

total=count(TEXT, a);

Similarly, the printf() on the next line also references DATA, when you really mean TEXT. If we change that too, the first part of your code ends up looking like this:

#include <stdio.h>
#include <string.h>
#define STRLEN 80

void searchCount(char *text, char z);
int count(char *data, char b);

int main(void)
{
    int total;
    char a;
    char text[STRLEN];

    printf("enter a string:");
    fgets(text, STRLEN, stdin);

    printf("find a character>>");
    scanf("%c", &a);

    searchCount(text, a);
    total = count(text, a);

    printf("%d found in the string %s", total, text);

    return 0;
}

I've also changed the case of your TEXT (and sole remaining DATA) to lower case, as that's a standard convention. Keep ALL CAPS just for manifest constants, like our STRLEN.

Are you happy with this code before we move on?

thank u so much for the code i think this looks okay what abt the function definition inside searchCount and Count function?

#include<stdio.h>
     #include<string.h>
     #define STRLEN 80
   
      void searchCount(char *text, char z);
      int count(char*data, char b);

      int main(){
      int total;
      char a;
      char *text[STRLEN];
      printf("enter a string:");
      fgets(text,STRLEN,stdin);
      printf("find a character>>");      
      scanf("%c",&a);
      searchCount(text,a);
      total=count(text,a);
      printf("%d character %c found in the string %s", total,a ,text);
      return 0;
      }

      void searchCount(char *text, char z)
      {
      int count=0;
      int i;
      for(i=0;i<strlen(text);++i)
      {
      if(text[i]==z)
      count++;}
      printf("The string has %d character including white space.\n",text,count);
      }
  
      //in here i tried to implement another function calls for counting the occurence of specified character
      int count(char *data, char b){
      int total=0;
      int j;
      for(j=0;j<strlen(data);j++){
      if(data[j]==b)
      total=total+j;}
      }

this one is final , the program can give output but not the correct one ><

OK, let's look at searchCount(). You've currently got:

void searchCount(char *text, char z)
      {
      int count=0;
      int i;
      for(i=0;i<strlen(text);++i)
      {
      if(text[i]==z)
      count++;}
      printf("The string has %d character including white space.\n",text,count);
      }

If you want this function to tell you how many occurrences of a particular char there are in a string, it's really not too far off. But look at your printf(); you are specifying a single, integer, parameter in the format string (%d), but trying to pass both a string ('text') and an integer ('count') to it. Try this (note: I've changed your printf() text to reflect what the function actually does):

void searchCount(char *text, char z)
{
    int count = 0;
    int i;

    for(i = 0; i < strlen(text); ++i)
    {
        if(text[i] == z)
            count++;
    }

    printf("The string contains '%c' %d times.\n", z, count);
}

OK, your turn ;-)

Your other count() function has two errors. Given that we've prototyped it as:

int count(char *data, char b);

can you tell me what the first problem with the actual function code is?

it works now thank u very much:)

i think i supposed to search the character inside the countSearch function
i should just distinguished the count function itself
btw where should i put the printf to give the output for numbers of characters that string ? i tried do this

#include<stdio.h>
     #include<string.h>
     #define STRLEN 80
   
      void searchCount(char *text, char z);
   

      int main(){
      int total;
      char a;
      char *text[STRLEN];
      printf("enter a string:");
      fgets(text,STRLEN,stdin);
      printf("find a character>>");      
      scanf("%c",&a);
      searchCount(text,a);
      printf("%d character %c found in the string %s", total,a ,text);
      return 0;
      }

      void searchCount(char *text, char z)
      {
      int count=0;
      int i;
      for(i=0;i<strlen(text);++i)
      {
      if(text[i]==z)
      count++;}
      printf("The string %s has %d character including white space.\n");
      printf("%d character %c found in the string %s", count,z ,text);

      }

to counting the number of characters in a string its still given error calculation

><

printf("The string %s has %d character including white space.\n");

How does this printf() [line #29] know what %s and %d refer to? It doesn't, as you've not told it what string and integer to print. You need to pass a reference to the string, and to its length, as parameters in that printf() call (hint: look at the printf() on the next line!)

If you also strip out line #17 -- you're doing the output in your searchCount() function now -- you should be done.

commented: Patience of a saint, RB! Well done. +2

If you also strip out line #17 -- you're doing the output in your searchCount() function now -- you should be done.

Actually, it would be better to strip the output out of the function. Let the function do its job (search) and only it's job. Let main() decide when and if the output should be displayed.

Actually, it would be better to strip the output out of the function. Let the function do its job (search) and only it's job. Let main() decide when and if the output should be displayed.

Normally I'd agree, but the OP was earlier failing to return a val from a function, and didn't seem to realise that that might be a problem... I was just trying to leave things very simple for them this time.

yeah i forgot to put arguments in the printf sry
btw i finish the code :) YEAYY thank u so much guys for ur help

and i can do it by putting

int total=0;
for(i=0;i<strlen(text)-1;i++){
total++;
 if(text[i]==z)
      count++;
      }
      printf("The string %s has %d character including white space.\n",total);
      printf("%d character %c found in the string %s", count,z ,text);

inside the function definition of searchCount

the thing i still dont get is why i can do strlen(text)-1 inside the for loop in order i can calculate the correct number of characters in the string instead of i do it in fgets? any1 can explain 2 me? i will really appreciate it:)

*note: i was finish it by luck :P i kept manipulating the code and of course u guys help me so much thankssssss

yeah i forgot to put arguments in the printf sry
btw i finish the code :) YEAYY thank u so much guys for ur help

and i can do it by putting

int total=0;
for(i=0;i<strlen(text)-1;i++){
total++;
 if(text[i]==z)
      count++;
      }
      printf("The string %s has %d character including white space.\n",total);
      printf("%d character %c found in the string %s", count,z ,text);

Sorry, but that won't work. Look at your first printf() -- you are still missing a parameter (the actual string, which you've popped a %s in there to hold).

the thing i still dont get is why i can do strlen(text)-1 inside the for loop in order i can calculate the correct number of characters in the string instead of i do it in fgets? any1 can explain 2 me? i will really appreciate it:)

fgets() doesn't tell you how many characters you typed. It will always return a null-terminated string; at most the number of chars specified in the second parameter, including the terminating '\0'.

Try this code:

#include <stdio.h>
#define MAXLEN 10

int main(void)
{
    char s[MAXLEN];

    do
    {
        printf("Type a string: ");
        fgets(s, MAXLEN, stdin);
        printf("Input received: %s\n", s);
    } while (*s != '\n');

    return 0;
}

Try running that, and entering short strings (< 9 chars). It does what you'd expect, no? [you can just type a carriage return on its own to quit the program]

OK. Now try entering a longer string and watch what happens. Can you explain what is happening when you type in a string longer than 8 chars?

when i typed abcde the output became:

enter a string: abcde
input received: abcde


bt when i put string more than 8 characters like
enter a string: abcdefghi
input received: abcdefghi
enter a string:input received:

i dont really get why the command is repeated again and without new line maybe because of while condition '\n' is counted to terminated the do while functions?

i dont really get why the command is repeated again and without new line maybe because of while condition '\n' is counted to terminated the do while functions?

OK. We've set aside 10 characters to store our input, and asked fgets() to get at most 10 characters.

fgets() will always append a string termination character ('\0') to what it returns.

When we enter 123456<return> we are asking fgets() to store the digits 1 through 6, plus our newline character (you pressed enter/return), plus the string termination char ('\0'). That's 8 characters in total. That fits into our 10 character buffer, so everything works as expected.

If we were to enter 123456abcdef<return> fgets() reads as much as it can. With a 10 char buffer, that's only 9 characters, as it always has to reserve one space to add the string termination char itself. So our little program would first print out 123456abc . That's 9 chars, plus the invisible '\0': 10 in total.

But there are still some extra chars left in the input buffer. As our program loops around, it reads those def . It then finds a newline character in the buffer, which fgets() knows means to stop getting input. The program then prints out what fgets() has given us, which are the 3 chars def and the <newline> char.

The potentially confusing case is where you enter 123456789<return> Here, the program prints out the digits 1 through 9 as expected, but then quits. Why?

The answer is that fgets() grabs as many characters as it can (up to our maximum), which in this case are the digits 1 through 9. It adds a string termination char, and returns those 10 characters. These are then printed out (remember you don't see the '\0').

But there is still a <newline> in the input buffer. Next time the program loops, fgets() grabs this, so we get a 'blank' output. We also find the program quits, as the first character of our input is a <newline> character ('\n'), which I've used in the while bit of the loop as an exit case.

Is that any clearer?

i passed overnight to get this, and ur explanations much2 better than any lecturers i knew. thank u very much for ur help :) now i move on to my next question on my assignment :)

hi all im stuck to my assignment

1. i want to know how to use function search in order i can search each character in a string then count the number of it.

for example: given : home alone
the output will be :

the string has 9 characters including the white space.

if i want to search character a in the string
the output will be

1 a found in the string home alone.

if i want to search y in the string the output will be

no y is found in the string home alone

so far this is the code that i made:

#include<stdio.h>
#include<string.h>

void searchCount(char*TEXT, char z);

int main(){
int string_size;
char a;

char name[]="HAPPY BIRTHDAY";
name[strlen(name)-1]='\0';
printf("find a character>>");
scanf("%c", &a);

searchCount(name,);  //this part i have to calling searchCount function but i have no idea which argument i have to pass in

printf("The string has %d characters including white space.",i);

return 0;
}

void searchCount(char *TEXT, char z){

//no idea to put in//

return count;
}

i think i have to use switch but serious i dont understand how to mix it with pointer,pls any idea?

#include <cstdlib>
#include <iostream>

using namespace std;
int strsearch(char* str, char* strname)
{
    int count=0;
    while(*strname!='\0')
    {
      if(*str==*strname)
      count++;
      *strname++;
    }
    return count;
}
int main(int argc, char *argv[])
{
    char *s="hello sir how are you";
//type what characters you want to search here in char*a
    char *a="o";
    cout<<strsearch(a,s)<<"times charatcer "<<*a<<" founded";
    cout<<endl;
    

    system("PAUSE");
    return EXIT_SUCCESS;
}
commented: don't post C++ code to a C problem.. and you didn't even address the question he was asking, the question that you quoted in your "response" .. total FAIL -1

Welcome to the forum, Rinku! :)

In the editing (advanced) window, whenever you post code, highlight it, and click on the [code] icon at the top of that window. The idea is to surround your code with these code tags.

That makes your code, stay looking like code, instead of being all squashed to the left side.

I wouldn't bother posting a C++ solution to a C assignment or question. These are coders (mostly students), who are taking a C class, and know very little/nothing yet, about C++, and can't turn C++ code in for credit, anyway.

Save the C++, for the C++ questions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.