Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- using namespace std;
- bool substring(char s1[], int p1, int p2, char s2[]) {
- // Verifica che i valori di p1 e p2 siano corretti
- if (p1 < 0 || p2 < 0 || p1 >= strlen(s1) || p2 >= strlen(s1)) {
- return false;
- }
- if(p1 > p2) {
- int tmp = p1;
- p1 = p2;
- p2 = tmp;
- }
- int len = p2 - p1 + 1;
- for (int i = 0; i < len; ++i) {
- s2[i] = s1[p1 + i];
- }
- s2[len] = '\0'; // Aggiunge il terminatore di stringa
- return true;
- }
- int main() {
- const int maxSize = 100;
- char s1[maxSize], s2[maxSize];
- int p1, p2;
- cout << "Inserisci una stringa: ";
- cin.getline(s1, maxSize);
- cout << "Inserisci la posizione iniziale (p1): ";
- cin >> p1;
- cout << "Inserisci la posizione finale (p2): ";
- cin >> p2;
- if (substring(s1, p1, p2, s2)) {
- cout << "La sottostringa tra le posizioni " << p1 << " e " << p2 << " è: " << s2 << endl;
- } else {
- cout << "Errore: valori di posizione non corretti." << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement