簡體   English   中英

如何將文本字符串轉換為 C 中的 int 以查找其中的部分?

[英]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] != 0stringAsArray[i] != '\0'相同,因此一旦您點擊 C 字符串的終止 NUL 字符,for 循環將結束.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM