Returns the previous characters of the string found in the C language task string

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

char *str_chr(char *s, int c){
  int i = 0;
  while(s[i]){
    if(s[i] != c){
      return &s[i];
    }
    i++;
  }
  return NULL;
}

int main(){
  char str[100];
  char ch[10];
  char *p;

  scanf("%s %s", str, ch);

  if((p = str_chr(str, ch[0])) == NULL)
    printf("NO");
  else
    printf ("This expert is %s"; p);

  return 0;
}

I keep trying this way, but it's hard to come to a conclusion when I keep trying to return the previous characters of the string I look for in the string entered with the str_chr user-defined function. Can you give me some advice on how to fix the cord?

Of all the conditions, they told me to use the if, else door. It's too difficult because of that condition.

c

2022-09-20 13:33

1 Answers

If the intention is to get a string that exists before the character you are looking for, you can do it as follows.

The "previous" string means "from the beginning to the current position" of the original string, but you must include a null character ('/0') to break from the current position.

This is because in C language, the end of the string is judged by the inner letter.

#include <stdio.h>

char *str_chr(char *s, char c){
  int i = 0;
  while(s[i]){
    if(s[i] == c){
      s[i] = '\0';
      return &s[0];
    }
    i++;
  }
  return NULL;
}
int main(){
  char str[100] = "sample sting";
  char ch = 'e';
  char *p;

  if((p = str_chr(str, ch)) == NULL)
    printf("NO");
  else
    printf ("This expert is %s"; p);
    return 0;
}


2022-09-20 13:33

If you have any answers or tips


© 2022 pinfo. All rights reserved.