StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Program #27 (U3): String Utilities without <string.h>
Download
  1. C Programming
  2. C Programming Practice
Program #26 (U3): Transpose and Symmetric Check : Program #28 (U3): Count Character Categories in a String
C Programming Practice

Task: Implement your own length, copy, compare, and reverse and call them via a small menu. Work only with character arrays and loops.

 
/* No <string.h>: implement strlen, strcpy, strcmp, strrev equivalents. */

#include <stdio.h>

 
int my_strlen(const char s[]) { int n=0; while(s[n] != '\0') ++n; return n; }

void my_strcpy(char d[], const char s[]) { int i=0; do { d[i] = s[i]; } while (s[i++]!='\0'); }

int my_strcmp(const char a[], const char b[]) { int i=0; while(a[i] && b[i] && a[i]==b[i]) ++i; return (a[i]-b[i]); }

void my_strrev(char s[]) { int i=0,j=my_strlen(s)-1; char t; while(i<j){ t=s[i]; s[i]=s[j]; s[j]=t; ++i; --j; } }

 
void read_line(char s[], int max) {

    int c, i=0;

    while ((c=getchar())!='\n' && c!=EOF) { if(i<max-1){ s[i++]=(char)c; } }

    s[i]='\0';

}

 
int main(void) {

    char s[256], t[256];

    int choice;

 
    printf("Enter a string: ");

    read_line(s, 256);

 
    printf("Menu: 1.Length  2.Copy(to t)  3.Compare with t  4.Reverse\n");

    printf("Enter choice: ");

    scanf("%d", &choice);

    getchar(); /* consume newline */

 
    switch(choice) {

        case 1: printf("Length = %d\n", my_strlen(s)); break;

        case 2: my_strcpy(t, s); printf("Copied to t: %s\n", t); break;

        case 3: printf("Enter t: "); read_line(t, 256); printf("Compare result = %d\n", my_strcmp(s,t)); break;

        case 4: my_strrev(s); printf("Reversed: %s\n", s); break;

        default: printf("Invalid choice.\n");

    }

    return 0;

}

 

 

Program #26 (U3): Transpose and Symmetric Check Program #28 (U3): Count Character Categories in a String
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website