使用 for 迴圈列印反序字串的 C 語言程式
下面我們編寫一個程式,在沒有預定義函式的情況下反轉句子。使用 for 迴圈,我們可以輕鬆地按相反的順序列印語句。
程式 1
#include<stdio.h> int main(){ char stmt[100]; int i; printf("enter the message:
"); for(i=0;i<stmt;i++){ stmt[i]=getchar(); //reading each char from console till enter or newline char is pressend if(stmt[i]=='
') break; } printf("the reverse statement is:
"); for(i--;i>=0;i--) //printing each char in reverse order putchar(stmt[i]); putchar('
'); return 0; }
輸出
enter the message: Hi welcome to my world the reverse statement is: dlrow ym ot emoclew iH
程式 2
這裡,我們將編寫一個使用 strrev 庫函式反轉字串的 C 語言程式 −
#include<stdio.h> #include<string.h> void main(){ //Declaring two strings// char result[50],string[25]; //Reading string 1 and String 2// printf("Enter String to be reversed : "); gets(string); //Reversing using library function// strrev(string); printf("The reversed string is : "); puts(string); }
輸出
Enter String to be reversed : Hi welcome to tutorials Point The reversed string is : tnioP slairotut ot emoclew iH
廣告