D
D
dandropov952018-08-28 13:22:31
C++ / C#
dandropov95, 2018-08-28 13:22:31

How to write a function to find a space in a string?

Like wrote, it seems like it works. But it seems that this is such a solution. Please tell me how to solve this problem better. It is necessary to return a pointer to the first found space, otherwise, if a space is not found, return NULL.

char * find_space(char * string)
{
  char ch;

  while (ch = *string++)
  {	
    if (ch == ' ')
        return &ch;
  }

  return NULL;
}

Or like this. But it still seems like it.
const char * find_space(const char * string)
{
  int i = 0;

  while (string[i] && string[i] != ' ')
    i++;

  if (string[i] != '\0')
    return string;

  return NULL;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
al_sh, 2018-08-28
@al_sh

char *findSpace(char *value)
{
    for(;value && *value && *value != ' '; ++value);
    return value && *value != '\0' ? value : nullptr;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question