Advertisement
buonaseva_fatelo

46_da_spiegare

Feb 10th, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. bool substring(char s1[], int p1, int p2, char s2[]) {
  7.     // Verifica che i valori di p1 e p2 siano corretti
  8.     if (p1 < 0 || p2 < 0 || p1 >= strlen(s1) || p2 >= strlen(s1)) {
  9.         return false;
  10.     }
  11.     if(p1 > p2) {
  12.         int tmp = p1;
  13.         p1 = p2;
  14.         p2 = tmp;
  15.     }
  16.  
  17.     int len = p2 - p1 + 1;
  18.     for (int i = 0; i < len; ++i) {
  19.         s2[i] = s1[p1 + i];
  20.     }
  21.     s2[len] = '\0'; // Aggiunge il terminatore di stringa
  22.  
  23.     return true;
  24. }
  25.  
  26. int main() {
  27.     const int maxSize = 100;
  28.     char s1[maxSize], s2[maxSize];
  29.     int p1, p2;
  30.  
  31.     cout << "Inserisci una stringa: ";
  32.     cin.getline(s1, maxSize);
  33.  
  34.     cout << "Inserisci la posizione iniziale (p1): ";
  35.     cin >> p1;
  36.     cout << "Inserisci la posizione finale (p2): ";
  37.     cin >> p2;
  38.  
  39.     if (substring(s1, p1, p2, s2)) {
  40.         cout << "La sottostringa tra le posizioni " << p1 << " e " << p2 << " è: " << s2 << endl;
  41.     } else {
  42.         cout << "Errore: valori di posizione non corretti." << endl;
  43.     }
  44.  
  45.     return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement