Program C ++ untuk Menghapus semua Karakter dalam String Kecuali Huruf.

0
(0)

Contoh 1: Hapus semua karakter kecuali huruf

Program ini mengambil input string (objek) dari pengguna dan menghapus semua karakter kecuali huruf.

#include 
using namespace std;

int main() {
    string line;
    string temp = "";

    cout << "Enter a string: ";
    getline(cin, line);

    for (int i = 0; i < line.size(); ++i) {
        if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
            temp = temp + line[i];
        }
    }
    line = temp;
    cout << "Output String: " << line;
    return 0;
}

Keluaran

Enter a string: p2'r"o@gram84iz./
Output String: programiz

Contoh 2: Hapus semua karakter kecuali huruf

Program di bawah ini mengambil input string (string C-style) dari pengguna dan menghapus semua karakter kecuali huruf.

#include 
using namespace std;

int main() {
    char line[100], alphabetString[100];
    int j = 0;
    cout << "Enter a string: ";
    cin.getline(line, 100);

    for(int i = 0; line[i] != ''; ++i)
    {
        if ((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z'))
        {
            alphabetString[j++] = line[i]; 

        }
    }
    alphabetString[j] = '';

    cout << "Output String: " << alphabetString;    
    return 0;
}

Keluaran

Enter a string: P2'r"o@gram84iz./
Output String: Programiz

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.