C 程式,列印字串中的 ASCII 值。


字元陣列稱為字串。

以下是字串的宣告

char stringname [size];

例如,char string[50]; 長度為 50 個字元的字串。

初始化

  • 使用單個字元常量。
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 使用字串常量。
char string[10] = “Hello”:;

訪問

有一個控制字串“%s”,用於訪問字串,直至遇到 ‘\0’。

我們用來列印給定字串在執行時的 ASCII 值的邏輯如下 −

while(str[i]!='\0'){
   printf("
ASCII Value of %c = %d", str[i], str[i]);    i++; }

示例

以下是列印給定字串的 ASCII 值的 C 程式 −

#include<stdio.h>
int main() {
   char string[50];
   int i=0;
   printf("Enter the Sentenc: ");
   gets(string);
   while(string[i]!='\0') {
      printf("
ASCII Value of %c=%d", string[i], string[i]);       i++;    }    getch();    return 0; }

輸出

執行上述程式後,會產生以下輸出 −

Enter the Sentence: Tutorials Point

ASCII Value of T = 84
ASCII Value of u = 117
ASCII Value of t = 116
ASCII Value of o = 111
ASCII Value of r = 114
ASCII Value of i = 105
ASCII Value of a = 97
ASCII Value of l = 108
ASCII Value of s = 115
ASCII Value of   = 32
ASCII Value of P = 80
ASCII Value of o = 111
ASCII Value of i = 105
ASCII Value of n = 110
ASCII Value of t = 116

更新於: 2021 年 3 月 25 日

8 千次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.