简体   繁体   English

如何实现字谜和回文功能来检查用户输入的单词?

[英]How can I implement my anagram and palindrome functions to check the words input by a user?

I got some help earlier fixing up one of the functions I am using in this program, but now I'm at a loss of logic. 在更早地修复此程序中使用的功能之一时,我得到了一些帮助,但现在我迷失了逻辑。

I have three purposes and two functions in this program. 在此程序中,我有三个目的和两个功能。 The first purpose is to print a sentence that the user inputs backwards. 第一个目的是打印用户向后输入的句子。 The second purpose is to check if any of the words are anagrams with another in the sentence. 第二个目的是检查句子中是否有任何单词与另一个字母相读。 The third purpose is to check if any one word is a palindrome. 第三个目的是检查是否有一个单词是回文。

I successfully completed the first purpose. 我成功地完成了第一个目标。 I can print sentences backwards. 我可以向后打印句子。 But now I am unsure of how I should implement my functions to check whether or not any words are anagrams or palindromes. 但是现在我不确定如何执行我的功能来检查任何单词是否是字谜或回文。

Here's the code; 这是代码;

/*
 * Ch8pp14.c
 *
 *  Created on: Oct 12, 2013
 *      Author: RivalDog
 *      Purpose: Reverse a sentence, check for anagrams and palindromes
 */

#include <stdio.h>
#include <ctype.h> //Included ctype for tolower / toupper functions
#define bool int
#define true 1
#define false 0

//Write boolean function that will check if a word is an anagram
bool check_anagram(char a[], char b[])
{
   int first[26] = {0}, second[26] = {0}, c = 0;
// Convert arrays into all lower case letters
   while(a[c])
   {
       a[c] = (tolower(a[c]));
       c++;
   }

   c = 0;

   while(b[c])
      {
       b[c] = (tolower(b[c]));
       c++;
      }

      c = 0;

   while (a[c] != 0)
   {
      first[a[c]-'a']++;
      c++;
   }

   c = 0;

   while (b[c] != 0)
   {
      second[b[c]-'a']++;
      c++;
   }

   for (c = 0; c < 26; c++)
   {
      if (first[c] != second[c])
         return false;
   }

   return true;
}

//Write boolean function that will check if a word is a palindrome
bool palindrome(char a[])
{
    int c=0, j, k;
    //Convert array into all lower case letters
    while (a[c])
    {
        a[c] = (tolower(a[c]));
        c++;
    }

    c = 0;
    j = 0;
    k = strlen(a) - 1;
    while (j < k)
    {
        if(a[j++] != a[k--])
            return false;
    }

    return true;
}

int main(void)
{
    int i = 0, j = 0, k = 0;
    char a[80], terminator;
    //Prompt user to enter sentence, store it into an array
    printf("Enter a sentence: ");
    j = getchar();
    while (i < 80)
    {
        a[i] = j;
        ++i;
        j = getchar();
        if (j == '!' || j == '.' || j == '?')
        {
            terminator = j;
            break;
        }
        else if(j == '\n')
        {
            break;
        }
    }
    while(a[k])
    {
        a[k] = (tolower(a[k]));
        k++;
    }
    k = 0;
    while(k < i)
    {
        printf("%c", a[k]);
        k++;
    }
    printf("%c\n", terminator);
    //Search backwards through the loop for the start of the last word
    //print the word, and then repeat that process for the rest of the words
    for(j = i; j >= 0; j--)
    {
        while(j > -1)
        {
            if (j == 0)
            {
                for(k=j;k<i;k++)
                    {
                        printf("%c", a[k]);
                    }
                printf("%c", terminator);
                    break;
            }
            else if (a[j] != ' ')
                --j;
            else if (a[j] == ' ')
                {
                    for(k=j+1;k<i;k++)
                        {
                            printf("%c", a[k]);
                        }
                    printf(" ");
                        break;
                }
        }
        i = j;
    }
    //Check if the words are anagrams using previously written function
    for( i = 0; i < 80; i++)
    {
        if (a[i] == ' ')
        {

        }
    }

    //Check if the words are palindromes using previously written function

return 0;
}

I was thinking that perhaps I could again search through the array for the words by checking if the element is a space, and if it is, store from where the search started to the space's index-1 in a new array, repeat that process for the entire sentence, and then call my functions on all of the arrays. 我在想,也许我可以通过检查元素是否为空格来再次在数组中搜索单词,如果是,则将搜索开始的位置存储到新数组中空间的index-1处,对整个句子,然后在所有数组上调用我的函数。 The issue I am seeing is that I can't really predict how many words a user will input in a sentence... So how can I set up my code to where I can check for anagrams/palindromes? 我看到的问题是我无法真正预测用户将在一个句子中输入多少个单词...那么,如何设置我的代码以检查字谜/回文?

Thank you everyone! 谢谢大家!

~RivalDog 〜RivalDog

Would be better,if you first optimize your code and make it readable by adding comments.Then you can divide the problem in smaller parts like 1.How to count words in a string? 如果先优化代码并通过添加注释使其可读性会更好。然后可以将问题分成较小的部分,例如1.如何计算字符串中的单词? 2.How to check whether two words are anagrams? 2.如何检查两个词是否是字谜? 3.How to check whether a word is palindrome or not? 3.如何检查单词是否是回文? And these smaller programs you could easily get by Googling. 而这些较小的程序可以通过Googling轻松获得。 Then your job will be just to integrate these answers. 那么您的工作将只是整合这些答案。 Hope this helps. 希望这可以帮助。

To check anagram, no need to calculate number of words and comparing them one by one or whatever you are thinking. 要检查字谜,无需计算单词数并将其一一比较或您在考虑什么。
Look at this code. 看这段代码。 In this code function read_word() is reading word/phrase input using an int array of 26 elements to keep track of how many times each letter has been seen instead of storing the letters itself. 在此代码函数中, read_word()使用包含26个元素的int数组读取单词/短语输入,以跟踪每个字母被查看了多少次,而不是存储字母本身。 Another function equal_array() is to check whether both array a and b (in main ) are equal (anagram) or not and return a Boolean value as a result. 另一个函数equal_array()用来检查数组ab (在main )是否相等(字谜),并返回一个布尔值作为结果。

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

void read_word(int counts[26]);
bool equal_array(int counts1[26],int counts2[26]);

int main()
{
    int a[26] = {0}, b[26] = {0};

    printf("Enter first word/phrase: ");
    read_word(a);
    printf("Enter second word/phrase: ");
    read_word(b);

    bool flag = equal_array(a,b);
    printf("The words/phrase are ");
    if(flag)
        printf("anagrams");
    else
        printf("not anagrams"); 

    return 0;
}

void read_word(int counts[26])
{
    int ch;
    while((ch = getchar()) != '\n')
    if(ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
        counts[toupper(ch) - 'A']++;
}

bool equal_array(int counts1[26],int counts2[26])
{
    int i = 0;
    while(i < 26)
    {
        if(counts1[i] == counts2[i])
            i++;
        else
            break;  
    }

    return i == 26 ? true : false;  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM