strreplace Fonksiyonunu Kullanmadan Cümle İçindeki Bir Kelimeyi Bulmak Ve Değiştirmek

mustaphos

MB Üyesi
Kayıt
14 Eylül 2015
Mesajlar
35
Tepkiler
8
Yaş
28
Meslek
Öğrenci
Üniv
Anadolu University
Merhabalar.
Bu gıcık kodu okul ödevim için yapmıştım.
Umarım yararlı olur.
İyi çalışmalar.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *bul_degistir(char *cumle, char *kelime1, char *kelime2);// Function prototype

void main()
{
char *cumle, *kelime1, *kelime2,*soncumle;//character arrays
cumle = (char *)malloc(sizeof(char));//allocation
printf("Please enter a sentence:\n");
gets(cumle);//gets cumle
soncumle = (char *)malloc(sizeof(char)*strlen(cumle));//allocation for other strings
kelime1 = (char *)malloc(sizeof(char)*strlen(cumle));
kelime2 = (char *)malloc(sizeof(char)*strlen(cumle));
printf("Find the word:");//gets substring
gets(kelime1);
printf("Replace with:");//gets substring for replacement
gets(kelime2);
soncumle = bul_degistir(cumle, kelime1, kelime2);//function call
puts(soncumle);
getch();
}

char *bul_degistir(char *cumle, char *kelime1, char *kelime2)
{
int x, kelime1uzunluk, kelime2uzunluk, fark;
char *kalan, *ilk, *kopya;
char *p = NULL;

p = strstr(cumle , kelime1);

while(p != NULL)
{
ilk = strstr(cumle, kelime1);// Where the kelime1 occure first
kelime1uzunluk = strlen(kelime1);// Length of kelime1
kelime2uzunluk = strlen(kelime2);// Length of kelime2

if (kelime1uzunluk > kelime2uzunluk)
{
kalan = &ilk[kelime1uzunluk];// Get where ilk variable's points array

for (x = 0; x < kelime2uzunluk; x++)
ilk[x] = kelime2[x];// Replace the string of kelime1 with kelime2

ilk[kelime2uzunluk] = '\0';// Last char is space
strcat(cumle, kalan);// Add kalan to cumle

}
else if (kelime1uzunluk < kelime2uzunluk)
{
fark = kelime2uzunluk - kelime1uzunluk;// Calculate lengths difference of kelime1 and kelime2
kalan = (char *)malloc(strlen(cumle)*sizeof(char));// Memory allocation for kalan string

for (x = 0; x < strlen(cumle); x++)
kalan[x] = ilk[kelime1uzunluk++];// Equalize kalan string and ilk string

for (x = 0; x < kelime2uzunluk; x++)
ilk[x] = kelime2[x];// Replace the string of kelime2

ilk[kelime2uzunluk] = '\0';// Last char is space
strcat(cumle, kalan);// Add kalan to cumle
}
else
{
for (x = 0; x < kelime1uzunluk; x++)
ilk[x] = kelime2[x];
}

p = strstr(cumle , kelime1);

}
return cumle;

}
 
Yukarı Alt