// ENGR 131, Monday 3:30 Recitation (Amanda Rohn) // Homework #8 - Fun With Strings // Solution // File: strfun.cpp // Contains definitions of string manipulation functions described in strfun.h #include "strfun.h" #include #include namespace m330 { // length finds the length of s int length(const char * s) { int L = 0; while(*s != '\0') { L++; s++; } return L; } // strpos returns the index of the first occurrence of b in s int strpos(const char * s, char b) { for(int i = 0; *s != '\0'; i++) { if(*s == b) return i; s++; } return -1; } // revstr returns the string s, reversed void revstr(char * s) { int L = length(s); char * rev = s; //make a new pointer to the first character in s char temp; //temporary swapping variable rev += (L-1); //move rev to the end of s for(int i=0; i <= L/2; i++) { temp = *s; //switch what rev and s are pointing to *s = *rev; *rev = temp; rev--; //move rev towards beginning of string s++; //move s towards end } s = rev; //bring s back to the beginning } // strrpos returns the position of the last occurrence of c in s int strrpos(const char * s, char c) { int i = 0, pos = 0; for(i = 0; s[i] != '\0'; i++) pos++; for(; i >= 0; i--) { if(s[pos] == c) return pos; pos--; } return -1; } // substr makes the substring from positions a through b void substr(char * s, int a, int b) { int L = length(s); assert(a < b); assert(b < L); //copy the substring for(int i=0; i < b - a + 1; i++) s[i] = s[a+i]; //make the rest of the places null for(int j = b-a+1; j < L; j++) s[j] = '\0'; } // trim removes whitespace from the beginning and end of s void trim(char * s) { int L = length(s); if(L==0) return; int begin = 0, end = L-1; //find index of first non-whitespace character for(int i = 0; i < L; i++) { if(!isspace(s[i])) { begin = i; break; } } //find index of last non-whitespace character for(int j = end; j >= begin; j--) { if(!isspace(s[j])) { end = j; break; } } //if there's no whitespace, return if(begin == 0 && end == 0) return; substr(s,begin,end); } // ucwords capitalizes the first character of each word in s void ucwords(char * s) { int L = length(s); for(int i=0; i < L; i++) { if(isspace(s[i]) && !isspace(s[i+1]) ) { s[i+1] = toupper(s[i+1]); } } } } // end namespace