简体   繁体   English

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

[英]How do I convert a text string to an int in C to find parts in it?

My current issue with this code has to do with the Punctuation Count if statement if(Text == '.' || Text == '?' || Text == '?') .我当前与此代码的问题与标点计数 if 语句有关if(Text == '.' || Text == '?' || Text == '?')

Is there a variable I can create to replace Text in this situation and allow the code to run its process?在这种情况下,我可以创建一个变量来替换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);
}

Is there a variable I can create to replace Text in this situation and allow the code to run its process?在这种情况下,我可以创建一个变量来替换 Text 并允许代码运行其进程吗?

  char c = Text[0];

A C string is basically just an array of char values. C 字符串基本上只是一个char值数组。 Eg the following two definitions are both valid:例如以下两个定义都是有效的:

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

Thus you can process any string as an array:因此,您可以将任何字符串作为数组处理:

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.
}

Note that stringAsArray[i] as a boolean expression is identical to stringAsArray[i] != 0 and to stringAsArray[i] != '\0' , so the for loop will end once you hit the terminating NUL character of the C string.请注意,作为 boolean 表达式的 stringAsArray[i stringAsArray[i]stringAsArray[i] != 0stringAsArray[i] != '\0'相同,因此一旦您点击 C 字符串的终止 NUL 字符,for 循环将结束.

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

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