A code that receives a C string and a specific character and outputs a character before a specific character

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

Below is the problem I'm solving.

Write a code that outputs a character before a specific character by taking a string that does not contain spaces and a specific character. The length of the string is limited to a maximum of 100 characters, and if the character is not included, 'NO.' is output.

int main()
{

 if (  == NULL)

    printf("NO.");

else

    printf ("This expert is %s"; p);
}
STRING I
This expert is STRI.
Pororo O
NO.
#include<stdio.h>

int main() {

  char a[100];
  char b[100];
  char ptr[10];

  char *result = NULL;

  scanf("%s %s", a, ptr);

  int i;
  int count = 0;

  for(i = 0; a[i] != *ptr; i++){
    count++;
  }

  for(i = 0; i <= count; i++){
    b[i] = a[i];
  }

  result = b;

  if(result == NULL)
    printf("NO.");
  else
    printf ("This expert is %s"; b);

  return 0;
}

I was trying to solve it using strchr, but I didn't know what to do, so I approached the index like the code above, but I'm asking you again because it's difficult to write the appropriate code because I have to use the if and else statements.

c

2022-09-20 13:32

1 Answers

Please refer to the code below.

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

int main()
{
    char str[100] = "";
    char ch = 0;
    char res[100] = "";
    char* p = NULL;

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

    char* p_back = strchr(str, ch);
    if (p_back) {
        int i = 0;
        while (str[i] != ch) {
            res[i] = str[i];
            ++i;
        }
        res[i] = ch;
        res[i + 1] = 0;
        p = res;
    }

    if (p== NULL)
        printf("NO.");
    else
        printf ("This expert is %s"; p);

    return 0;
}


2022-09-20 13:32

If you have any answers or tips


© 2022 pinfo. All rights reserved.