//Demonstration of different string functions //Lecture 11, CSE 374, Spring 2017 #include #include //this is called strlen in the library //return the length of the string (number of non-null characters) int length(char* str) { int i = 0; while (str[i] != '\0') { i++; } return i; } //end the string str so it has len characters //only call if len is in range of the string void truncate(char* str, int len) { str[len] = '\0'; } //copy a string from dest to source //TODO: not quite finished void copy(char* dst, char* src) { int i = 0; while (src[i] != '\0') { dst[i] = src[i]; i++; } dst[i] = '\0'; } //test our functions here int main() { char* berry = "Blueberry"; char* empty = ""; char* long_string = "First line \n Second line"; char* weird_string = "Thiu\bs has a backspace in it"; printf("Length of %s is: %d\n", berry, length(berry)); printf("Length of %s is: %d\n", empty, length(empty)); printf("Length of %s is: %d\n", long_string, length(long_string)); printf("Length of %s is: %d\n", weird_string, length(weird_string)); char newberry[10]; for (int i = 0; i < 10; i++) { newberry[i] = berry[i]; } truncate(newberry, 4); printf("truncated to %s, length now: %d\n", newberry, length(newberry)); char copy_test[10]; copy(copy_test,berry); printf("copied berry string into copy_test: %s\n", copy_test); return 0; }