cs1713-day4-prog5.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (C) 2020, 2019, 2018, 2017 Girish M
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. * MA 02110-1301, USA.
  17. *
  18. */
  19. /*---------------------------------------------------------------------------
  20. Name: Girish M
  21. Roll number: cs1713
  22. Date: 1 August 2017
  23. Program description: Let s and t be strings containing at most 100 characters.
  24. Implement the following functions in C:
  25. (a) strlen(s): returns the length of s, i.e., the number of characters
  26. present in s;
  27. (b) strcmp(s, t): returns 1 if s and t are identical, 0 otherwise;
  28. (c) diffByOne(s, t): returns 1 if s and t are of the same length, and
  29. differ in exactly one position, 0 otherwise.
  30. Acknowledgements:
  31. ---------------------------------------------------------------------------*/
  32. #include <stdio.h>
  33. int strlength(char* str)
  34. {
  35. int len=0;
  36. while(*str++ != '\0')
  37. len++;
  38. return len;
  39. }
  40. int strcompare(char* s, char* t)
  41. {
  42. while(*s != '\0')
  43. {
  44. if(*s != *t)
  45. {
  46. return 0;
  47. }
  48. s++;
  49. t++;
  50. }
  51. return 1;
  52. }
  53. int diffByOne(char* s, char* t)
  54. {
  55. int numDiff=0;
  56. if(strlength(s) == strlength(t))
  57. {
  58. while(*s != '\0')
  59. {
  60. if(*s != *t)
  61. {
  62. numDiff++;
  63. }
  64. s++;
  65. t++;
  66. }
  67. if(numDiff == 1)
  68. return 1;
  69. else
  70. return 0;
  71. }
  72. else
  73. return 0;
  74. }
  75. int main(int argc, char* argv[])
  76. {
  77. //const int size_str = 100;
  78. if(argc == 3)
  79. {
  80. printf("\nstrlen(%s) is %d\n", argv[1], strlength(argv[1]));
  81. printf("\nstrlen(%s) is %d\n", argv[2], strlength(argv[2]));
  82. printf("\nstrcmp(%s, %s): %d\n", argv[1], argv[2], strcompare(argv[1], argv[2]));
  83. printf("\ndiffByOne(%s, %s): %d\n", argv[1], argv[2], diffByOne(argv[1], argv[2]));
  84. }
  85. else
  86. printf("\nUsage: ./cs1713-day3-prog1.o str1 str2\n");
  87. return 0;
  88. }