Folosind pointeri să se scrie o funcţie C care returnează lungimea unui şir de caractere (funcţia strlen –cu pointeri!).
#include<stdio.h>
#include<string.h>
int my_strlen(char *s) {
int cnt = 0;
while (*s++ != '\0' ) {
cnt++;
}
return cnt;
}
int main()
{
char astr[80];
puts ("Please enter a string of 40 characters or fewer.");
scanf ("%40[^\n]s", astr);
printf("a string = %s\n", astr);
printf("length = %d\n", my_strlen(astr));
return 0;
}
Folosind pointeri să se scrie o funcție C care primind ca si parametru 2 șiruri de caractere returnează un număr negativ dacă primul sir este mai mic, 0 dacă cele 2 siruri sunt egale si un număr pozitiv dacă primul sir este mai mare decât al 2-lea. Comparațiile sunt lexicografice. (implementare pentru funcția strcmp –cu pointeri!).
#include<stdio.h>
#include<string.h>
int my_strcmp(char *s, char *d) {
while( *s != '\0' || *d != '\0' ) {
if (*s > *d) {
return 1;
}
if (*s < *d) {
return -1;
}
// top are equal ... continue
s++;
d++;
}
if (*s == '\0' && *d == '\0') {
return 0;
}
// adjust the result if one of the string was consumed
return (*s == '\0') ? -1 : 1;
}
int main()
{
char astr[40];
char bstr[40];
puts ("Please enter a string of 40 characters or fewer.");
scanf ("%40[^\n]s\n", astr);
printf("a string = %s\n", astr);
puts ("Please enter a string of 40 characters or fewer.");
scanf (" %40[^\n]s\n", bstr);
printf("b string = %s\n", bstr);
printf("result = %d\n", my_strcmp(astr, bstr));
return 0;
}
Folosind pointeri să se scrie o funcție C care primind ca și parametru 2 siruri de caractere, le concatenează cu obținerea noului sir in primul argument al funcției (implementare pentru funcția strcat –cu pointeri!).
#include<stdio.h>
#include<string.h>
char *my_strcat(char *s, char *d) {
char *cs = s;
// iterate until end of s
while (*cs != '\0') {
cs++;
}
// append the second char. We assume we have enough space
while (*d != '\0') {
*cs++ = *d++;
}
// terminate the string
*cs = '\0';
return s;
}
int main()
{
char astr[80];
char bstr[40];
puts ("Please enter a string of 40 characters or fewer.");
scanf ("%40[^\n]s", astr);
printf("a string = %s\n", astr);
puts ("Please enter a string of 40 characters or fewer.");
scanf (" %40[^\n]s", bstr);
printf("b string = %s\n", bstr);
printf("result = %s\n", my_strcat(astr, bstr));
printf("result = %s\n", astr);
return 0;
}