Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สลับอักขระทั้งหมดในสตริงใน C++


โปรแกรมนี้แปลอักขระของสตริงเป็นตัวพิมพ์ใหญ่ อย่างไรก็ตาม งานนี้สามารถทำได้ง่ายโดยใช้เมธอด toUpper() ของไลบรารีคลาส c++ แต่ในโปรแกรมนี้ เราดำเนินการนี้โดยการคำนวณค่า ASCII ของอักขระเป็นตัวพิมพ์ใหญ่ อัลกอริทึมมีดังนี้

อัลกอริทึม

START
   Step-1: Declare the array of char
   Step-2: Check ASCII value of uppercase characters which must grater than A and lesser than Z
   Step-3: Check ASCII value of lower characters which must grater than A and lesser than Z
END

วิธี toggleChar() รับอาร์เรย์ของอักขระเป็นอินพุต จากนั้นข้ามผ่านลูปเพื่อให้แน่ใจว่าค่า ASCII ของอักขระที่ป้อนนั้นอยู่ระหว่าง A ถึง Z หรือไม่ดังต่อไปนี้

ตัวอย่าง

#include<iostream>
using namespace std;
void toggleChars(char str[]){
   for (int i=0; str[i]!='\0'; i++){
      if (str[i]>='A' && str[i]<='Z')
         str[i] = str[i] + 'a' - 'A';
      else if (str[i]>='a' && str[i]<='z')
         str[i] = str[i] + 'A' - 'a';
   }
}
int main(){
   char str[] = "ajay@kumar#Yadav";
   cout << "String before toggle::" << str << endl;
   toggleChars(str);
   cout << "String after toggle::" << str;
   return 0;
}

สตริงที่ให้มามีอักขระเกือบทั้งหมดเป็นตัวพิมพ์เล็กซึ่งจะถูกแปลงเป็นตัวพิมพ์ใหญ่ดังนี้

ผลลัพธ์

String before toggle::ajay@kumar#Yadav
String after toggle::AJAY@KUMAR#yADAV