From 305771b20cb49f3b7dd0fc64cf493620fd1f4096 Mon Sep 17 00:00:00 2001 From: Bobbi Webber-Manners Date: Sat, 5 May 2018 00:05:41 -0400 Subject: [PATCH] New example - string handling --- String-Handling-Example.md | 89 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 String-Handling-Example.md diff --git a/String-Handling-Example.md b/String-Handling-Example.md new file mode 100644 index 0000000..6f116d0 --- /dev/null +++ b/String-Handling-Example.md @@ -0,0 +1,89 @@ +Simple example which defines `strlen()`, `strcpy()`, `strcat()` and `strcmp()` functions in EightBall, which work the same way as their namesakes in C. +``` +byte msg1[100]="Enter your first name> " +byte msg2[100]="Enter your last name> " +byte s1[100]={} +byte s2[100]={} +byte full[200]={} +byte space[2]=" " + +pr.str msg1 +kbd.ln s1,100 +pr.msg "'"; pr.str s1; pr.msg "' has "; pr.dec strlen(s1); pr.msg " chars"; pr.nl +pr.str msg2 +kbd.ln s2,100 +pr.msg "'"; pr.str s2; pr.msg "' has "; pr.dec strlen(s2); pr.msg " chars"; pr.nl +call strcpy(full,s1) +call strcat(full,space) +call strcat(full,s2) +pr.msg "'"; pr.str full; pr.msg "' has "; pr.dec strlen(full); pr.msg " chars"; pr.nl +pr.msg "Comparison s1:s2 ... "; pr.dec.s strcmp(s1,s2); pr.nl +end + +' +' Return length of null-terminated string +' +sub strlen(byte str[]) + word i=0 + while str[i] + i=i+1 + endwhile + return i +endsub + +' +' Copy null-terminated string from src to dst +' +sub strcpy(byte dst[], byte src[]) + word i=0 + while src[i] + dst[i]=src[i] + i=i+1 + endwhile +endsub + +' +' Append null-terminated string src to dst +' +sub strcat(byte dst[], byte src[]) + word i=0 + word j=0 + while dst[i] + i=i+1 + endwhile + while src[j] + dst[i]=src[j] + i=i+1 + j=j+1 + endwhile +endsub + +' +' Compare null-terminated string s1 to s2 +' Return -1 if s1 < s2 +' Return 0 if s1 == s2 +' Return +1 if s1 > s2 +' +sub strcmp(byte s1[], byte s2[]) + word i=0 + while 1 + if ((!s1[i])&&(!s2[i])) + return 0 + endif + if (!s1[i]) + return -1 + endif + if (!s2[i]) + return 1 + endif + if (s1[i]s2[i]) + return 1 + endif + i=i+1 + endwhile +endsub + +``` \ No newline at end of file