78 lines
2.8 KiB
HTML
78 lines
2.8 KiB
HTML
<!--
|
|
AUTORE: Manuel Vichi 3^AIN
|
|
Esercizio 1 Stringhe: conta le occorrenze dei vari caratteri e le restituisce in una tabella
|
|
-->
|
|
<!DOCTYPE html>
|
|
<html lang="it">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Conta Occorrenze Lettere</title>
|
|
<style>
|
|
table {
|
|
border-collapse: collapse;
|
|
width: 25%;
|
|
}
|
|
table, th, td {
|
|
border: 1px solid black;
|
|
}
|
|
th, td {
|
|
text-align: center;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1>Conta le Occorrenze delle Lettere</h1>
|
|
<label for="inputString">Inserisci una stringa:</label>
|
|
<br>
|
|
<input type="text" id="inputString" placeholder="Scrivi qui...">
|
|
<br>
|
|
<button onclick="contaOccorrenze()">Conta Occorrenze</button>
|
|
<h2>Occorrenze delle Lettere</h2>
|
|
<table id="letterTable">
|
|
<thead>
|
|
<tr>
|
|
<th>Lettera</th>
|
|
<th>Occorrenze</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
</tbody>
|
|
</table>
|
|
<script>
|
|
function contaOccorrenze() {
|
|
const inputString = document.getElementById('inputString').value.toLowerCase();
|
|
const occorrenze = {};
|
|
// Memorizza le occorrenze delle lettere in un array
|
|
var num = 0;
|
|
for (let char of inputString) {
|
|
if (char >= 'a' && char <= 'z') {
|
|
occorrenze[char] = (occorrenze[char] || 0) + 1;
|
|
num++;
|
|
}
|
|
}
|
|
//Controlla se la stringa è vuota
|
|
if (num == 0) {
|
|
alert("La stringa è vuota, oppure contiene caratteri che non sono lettere.");
|
|
return;
|
|
}
|
|
const tableBody = document.getElementById('letterTable').getElementsByTagName('tbody')[0]; // Ottiene le righe su cui lavorare
|
|
tableBody.innerHTML = ''; // Inizializzazione vuota
|
|
for (let letter = 'a'.charCodeAt(0); letter <= 'z'.charCodeAt(0); letter++) {
|
|
const letterChar = String.fromCharCode(letter); // Controlla le occorrenze di ogni lettera dell'alfabeto
|
|
//console.log(letterChar);
|
|
if (occorrenze[letterChar]) {
|
|
const row = tableBody.insertRow(); // Inserisce una riga
|
|
// Imposta la lettera nella colonna 0 della riga
|
|
const cellLetter = row.insertCell(0);
|
|
cellLetter.textContent = letterChar.toUpperCase();
|
|
// Imposta il numero di occorrenze nella colonna 1 della riga
|
|
const cellOccorrenze = row.insertCell(1);
|
|
cellOccorrenze.textContent = occorrenze[letterChar];
|
|
}
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html>
|