如何在 C 中将文本字符串转换为 int 以在其中查找部分?



我目前对这段代码的问题与标点符号计数有关,如果语句if(Text == '.' || Text == '!' || Text == '?')

在这种情况下,我是否可以创建一个变量来替换Text并允许代码运行其进程?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(void)
{  //Letter Count Section
string Text = get_string("Text: "); //Gets Text
char Checker = isalpha(Text); // Checks for letters
int Count = strlen(&Checker); //Counts letters
//Space Count Section
int Spaces = 0; //Declares Variable
if(isspace(Text)){ //Checks for Spaces
Spaces += 1; //Adds +1 to Variable if Space
}
//Punctuation Count
if(Text == '.' || Text == '!' || Text == '?')
Punctuation += 1;
float Sentence = (Count/(Spaces*100));
float Letters = (Punctuation/(Spaces*100));
printf("n%f",Sentence);
printf("n%f",Letters);
// Formula  
int gradelvl = (0.0588 * Letters - 0.296 * Sentence - 15.8);
// End Result  
printf("nGradelevel: %in",gradelvl);
}
在这种情况下,

我可以创建一个变量来替换文本并允许代码运行其进程吗?

char c = Text[0];

C 字符串基本上只是一个char值的数组。 例如,以下两个定义都是有效的:

char * stringAsPtr = "Hello World";
char stringAsArray[] = "Hello World";

因此,您可以将任何字符串作为数组进行处理:

for (size_t i = 0; stringAsArray[i]; i++) {
char c = stringAsArray[i];
// Do something with c, e.g. check if it is a space 
// and increase your space counter if it is.
}

请注意,作为布尔表达式的stringAsArray[i]stringAsArray[i] != 0stringAsArray[i] != ''相同,因此一旦您命中 C 字符串的终止 NUL 字符,for 循环就会结束。

相关内容

最新更新