首页 > 解决方案 > 在 C 中搜索字母或字符串

问题描述

我对 C 编程非常陌生。我在其他 Web 开发语言方面拥有广泛的背景。我在网上查了简单的数字游戏,复制粘贴。为了检查我的理解,我也评论了一些东西。我尝试调试并意识到当输入一个字符串时,整个代码都会中断。我只需要快速回答一些非常基本的问题:如何在字符串中查找字母。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*Attempting to optimize number game in C*/
// immediate bug: runs FOREVER if text is entered


int main(void) {
    srand(time(NULL)); //I do not know 
    int r = rand() % 10 + 1; //Random number
    int correct = 0; //number correct from guess
    int guess; // Instance of guess
    int counter = 0; // Counter; how many tries
    const char* characters["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];// this is my var/*
    int c = 0, count[26] = { 0 }, x;
    */

    char string = [100];
    printf("Guess my number! "); // Does not need to repeat because of conditional statements below...

    do { //Runs at least once... [
        scanf("%d", &guess); // Takes in a number %d = int  
/*
        while (string[c] != '\0') {
            if (string[c] >= 'a' && string[c] <= 'z') {
                x = string[c] - 'a';
                count[x]++
            }

            c++;
        }
*/
        if (guess ==)
        if()

        if (guess == r) {  // Check if true 
            counter++; // Increment counter by 1
            printf("You guessed correctly in %d tries! Congratulations!\n", counter); // 
            correct = 1;
        }

        if (guess < r) { // check if less than
            counter++;
            printf("Your guess is too low. Guess again. ");
        }

        if (guess > r) { // check if more than 
            counter++;
            printf("Your guess is too high. Guess again. ");
        }
    } while (correct == 0); // If correct is null. ]

    return 0;
}

标签: cstringsearch

解决方案


标准C库有很多字符串操作函数,如strcpy、strncpy、strlen、strchr、strcat等。您可以使用“strchr”函数在字符串中查找字母。例如:

#include <stdio.h>
#include <string.h>
int main()
{
   const char *astring="Stack Owerflow"; 
   char *ptr = strchr(astring, 'O');
   printf("Found:%c on position: %d\n",*ptr, ptr-astring);
}

/* 输出:找到:O 在位置:6 */


推荐阅读