c - 在 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;
}
解决方案
标准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 */
推荐阅读
- iis-10 - HTTP 错误 500.19 - 设置 iis 站点时出现内部服务器错误
- python - xpath 无法与 Selenium (python) 一起正常工作
- amazon-s3 - Gatsby 公用文件夹结构不能很好地与 S3 静态网站托管配合使用
- python - GroupBy Dataframe 按一列并根据另一列获取计数
- python - 从 for 循环将多条线绘制到一个图上
- pandas - 日期列移动并且不再可调用
- python - tkinter 在类之间共享实例变量
- reactjs - 如何使用 React Native 中的事件侦听器和挂钩检查是否按下/按住某个键?
- python - 在 Python 中异步运行函数的多个变体
- python - 如何让这个 python GUI 运行这个可执行文件?