Create your own version of strncpy(s1,s2,n) function - C String

C examples for String:String Function

Introduction

strncpy(s1,s2,n) copies exactly n characters from s2 to s1, truncating s2 or padding it with extra null characters as necessary.

The target string may not be null-terminated if the length of s2 is n or more.

Demo Code

#include <stdio.h>

#define LIMIT 50//w w w .  j  a va  2 s . com

char * mystrcpy(char *s1, char *s2, int n);
char * get(char *string, int n);
void clear_string(char * string, int n);

int main(void)
{
  char s1[LIMIT];
  char s2[LIMIT];
  int n;

  printf("Enter a string to copy: ");
  get(s2, LIMIT);
  while (s2[0] != '\0'){
    printf("How many characters do you want to copy? (maximum %d) ", LIMIT);
    scanf("%d", &n);

    while (getchar() != '\n')
      continue;

    if (n > LIMIT)
      n = LIMIT;

    printf("Original string: %s\n", s2);
    mystrcpy(s1, s2, n);
    printf("Copy: %s\n", s1);

    clear_string(s1, LIMIT);

    printf("Enter a string to copy (empty line to quit): ");
    get(s2, LIMIT);
  }

  puts("Bye");

  return 0;
}
// copy n characters from s2 to s1, if length of s2 is n or greater then s1 may not be null terminated
char * mystrcpy(char *s1, char *s2, int n){
  int i = 0;
  // copy n characters or until null char
  while (s2[i] != '\0' && i < n){
    s1[i] = s2[i];
    i++;
  }
  // if i < n pad s1 with null character
  while (i < n)
  {
    s1[i] = '\0';
    i++;
  }

  return s1;
}
// wrapper for fgets that replaces first newline with null
char * get(char *string, int n){
  char *return_value = fgets(string, n, stdin);

  while (*string != '\0'){
    if (*string == '\n'){
      *string = '\0';
      break;
    }
    string++;
  }

  return return_value;
}
// replace first n characters in string with nulls
void clear_string(char *string, int n){
  for (int i = 0; i < n; i++)
    string[i] = '\0';
}

Result


Related Tutorials