Как найти начальные буквы в строке. Я получаю ошибки в программе ниже - PullRequest
0 голосов
/ 28 мая 2020
#include <stdio.h>
#include <string.h>
void printfletter(char *);``
int main ()
{
    char a[50]="where are you";
    printfletter(a);
    return 0;
}
void printfletter(char *p)
{
    int i;
    printf("%c",*p);
    for (i=1;*(p+i)!='\0';i++)
    {
        if (*(p+i)==32)
        {
            printf("%c",*(++p));
        }   
    }
}

Программа должна вывести все начальные буквы в строке. Я должен получить вывод как «путь» (w-where, a-are, y-you). Но я получаю «где». Я пытался реализовать это с помощью функций и указателей.

Ответы [ 2 ]

0 голосов
/ 28 мая 2020

Я предлагаю функцию, подобную этой:

// Argument is a constant pointer to constant character, because
// we neither modify the pointer nor modify the data it points to
void printfletter(const char * const p)
{
    if (p == NULL)
    {
        // The caller passed a null pointer
        return;  // Don't print anything, just return from the function
    }

    size_t i;  // Used as index into the string

    // First skip over all leading spaces, in case there is any
    for (i = 0; p[i] != '\0'; ++i)
    {
        // If the current character is not a space, then break out of the loop
        if (!isspace(p[i]))
        {
            break;
        }
    }

    if (p[i] == '\0')
    {
        // All of the string was space, no letters or anything else
        return;  // Don't print anything
    }

    // State variable, to say if the last character checked was a space
    bool last_was_space = true;  // Initialize to true, to print the first character

    // Iterate over all character in the null-terminated string
    // We reuse the index variable i, it will already be positioned at the
    // next character to check
    for (; p[i] != '\0'; ++i)
    {
        // If the current character at index i is a space...
        if (isspace(p[i]))
        {
            // ... then set the state variable
            last_was_space = true;
        }
        // Otherwise, if the last character was a space...
        else if (last_was_space)
        {
            // ... then print the current character
            putchar(p[i]);

            // And reset the state
            last_was_space = false;
        }
        // Else do nothing
    }
}

Вышеупомянутая функция должна печатать первый символ каждого «слова», разделенного пробелами.

Со строкой, которую вы показываете ("where are you") печатает way.

0 голосов
/ 28 мая 2020

Сначала удалите последние два символа в

void printfletter(char *);``

, чтобы он скомпилировался. Затем обратите внимание, что *(++p) всегда будет выбирать следующий символ в массиве. Вам действительно нужен (i + 1) -й символ, поэтому замените строку printf на

        printf("%c",p[i+1]);

. Это даст вам желаемый результат. Я бы порекомендовал также убедиться, что ваш код не демонстрирует неопределенное поведение, если вы скармливаете ему пустую строку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...