[英]How do I convert a text string to an int in C to find parts in it?
我当前与此代码的问题与标点计数 if 语句有关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: %i\n",gradelvl);
}
在这种情况下,我可以创建一个变量来替换 Text 并允许代码运行其进程吗?
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.
}
请注意,作为 boolean 表达式的 stringAsArray[i stringAsArray[i]
与stringAsArray[i] != 0
和stringAsArray[i] != '\0'
相同,因此一旦您点击 C 字符串的终止 NUL 字符,for 循环将结束.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.