/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#define MAX_LINE_LEN 1024
/* Reads a line of characters from standard input and copies
them into dest. Returns the number of characters written into
dest, including the terminating null character. The function
stops copying characters if it encounters the newline character
('\n') or EOF (i.e., the line ends) or if lim-1 characters have been
read (to allow space for a terminating null character). */
int csc225_getline(char dest[], int lim)
{
int c = EOF;
int i = 0;
for (i; i < lim - 1; i++)
{
c = getchar();
if (c == EOF || c == '\n')
break;
dest[i] = c;
}
if (c == '\n')
{
dest[i++] = c;
}
dest[i] = '\0';
return i;
}
/* Lexicographically (i.e., in dictionary order) compares
22 strings s1 and s2 (using simply the order of ASCII character
23 codes as the order of characters), up to a limit of n characters.
24 Returns -1, 0, 1 if s1 is less than, equal to, or greater than s2. */
int csc225_strncmp(char s1[], char s2[], int n)
{
/* WRITE YOUR CODE HERE */
for(int i = 0; i<n;i++)
{
if(s1[i] > s2[i])
{
return 1;
}
if(s1[i] < s2[i])
{
return -1;
}
}
return 0;
}
/* Copies up to n characters from the string src to the string dest.
45 WARNING: If no terminating null character is in the first n characters
46 of src, then dest will not be null terminated. */
void csc225_strncpy(char dest[], char src[], int n)
{
/* WRITE YOUR CODE HERE */
for(int i = 0; i < n; i ++)
{
dest[i] = src[i];
if((src[i] == '\0') || (src[i] == '\n'))
{
break;
}
}
}
int main()
{
char name1[100];
char name2[100];
printf("String Compare:\n");
printf("Enter string 1: ");
scanf("%s", name1);
printf("Enter string 2: ");
scanf("%s", name2);
int result = csc225_strncmp(name1, name2, 10);
printf("result = %d\n", result);
if(result == -1)
{
printf("So, s1 is less than s2\n");
}
if(result == 1)
{
printf("So, s1 is greater than s2\n");
}
if(result == 0)
{
printf("So, s1 is equal to s2\n");
}
int num_of_copy;
char dest[MAX_LINE_LEN];
char src[MAX_LINE_LEN];
printf("String Copy:\n");
printf("Enter dest (string you want to copy to: ");
scanf("%s", dest);
int n = csc225_getline(dest, MAX_LINE_LEN);
printf("Enter src (string you want to copy from): ");
scanf("%s", src);
printf("before=%s\n", dest);
printf("Enter number of letters you want to copy from src to dest (max should be num of letters in src):");
scanf("%d", &num_of_copy);
csc225_strncpy(dest, src, num_of_copy);
printf("after=%s\n", dest);
return 0;
}