不使用内置函数分割数组

问题描述 投票:1回答:2

下面的代码旨在采用输入字符串,例如My name is Smith并输出

My 
name 
is 
Smith

并且还必须排除诸如:, . and space之类的东西,只是这三个,但相反,它会输出,我不允许使用诸如strlenstrtok之类的任何东西

My
y

name
ame 
me
e

is
s

Smith
mith
ith
th
h

我已经在代码中到处搜索了错误,但似乎无法解决

int main()
{
    int wordSize = 0;
    char str[81];
    char* ptr_to_word[81];

    gets_s(str);

    for (char* res_p = &(str[0]); *res_p != '\0'; res_p++) {
        if ((*res_p != '.') || (*res_p != ',') || (*res_p != ' '))
        {
            ptr_to_word[wordSize] = res_p;
            wordSize++;
        }
    }

    if (wordSize == 0)
    {
        printf("no solution");
    }

    else
    {
        for (int i = 0; i < wordSize; i)
        {
            char* a = ptr_to_word[i];
            while ((*a != '.') && (*a != ',') && (*a != ' ') && (*a != '\0'))
            {
                printf("%c", *a);
                a++;
            }
            printf("\n");
        }
    }
    return 0;
}
c loops tokenize c-strings
2个回答
2
投票

在此循环中的if语句的情况下

for (char* res_p = &(str[0]); *res_p != '\0'; res_p++) {
    if ((*res_p != '.') || (*res_p != ',') || (*res_p != ' '))
    {
        ptr_to_word[wordSize] = res_p;
        wordSize++;
    }
}

您必须使用逻辑AND运算符,而不是类似的逻辑OR运算符

    if ((*res_p != '.') && (*res_p != ',') && (*res_p != ' '))

尽管如此,循环在任何情况下都是错误的,因为变量wordSize不计算单词,而是计算不等于if语句中列出的字符的每个字符。

要输出单独的单词,无需声明一个指向单词开头的指针数组。您可以在找到每个单词后立即输出每个单词。

这是一个非常简单的演示程序。

#include <stdio.h>

int main(void) 
{
    enum { N = 81 };
    char s[N];

    fgets( s, N, stdin );

    for ( const char *p = s; *p; )
    {
        int wordSize = 0;
        while ( *p && *p != '.' && *p != ',' && *p != ' ' && *p != '\t' && *p != '\n' )
        {
            ++wordSize;
            ++p;
        }

        if ( wordSize )
        {
            printf( "%.*s\n", wordSize, p - wordSize );
        }
        else
        {
            ++p;
        }
    }

    return 0;
}

如果输入“我的名字是史密斯”,则程序输出可能看起来像]]

My
name
is
Smith

我在定界符列表中附加了制表符'\t'和换行符'\n',可以通过函数fgets将其插入输入字符串中。


1
投票

首先,这种情况

© www.soinside.com 2019 - 2024. All rights reserved.