字符串操作
#include<iostream>using namespace std; // 字符串长度函数int strLength(char *s){ int i=0; while(s[i] != '\0'){ i++; } return i;} // 字符串连接函数int strCincat(char *s1, char *s2, char *s){ int i=0; int j=0; while(s1[i] != '\0'){ s[i] = s1[i]; i++; } while(s2[j] != '\0'){ s[i] = s2[j]; i++; j++; } s[i] = '\0'; // 串结束标志 return 1; } // 子串函数int strsub(char *t, char *s, int i, int len){ int slen; slen = strLength(s); if(i<1 || i>slen || len<0 || len>slen-i+1){ return 0; } int j=0; for(j;j<len;j++){ t[j] = s[i-j+1]; } t[j] = '\0'; return 1;} // 字符串比较函数int strComp(char *s1, char *s2){ int i=0; while(s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0'){ i++; } return (s1[i] - s2[i]);} // 字符串匹配函数int strFind(char *s, char *t){ int i=0; int j=0; while(s[i] != '\0' && t[j] != '\0'){ if(s[i] == t[j]){ i++; j++; }else{ i = i-j+1; j = 0; } } if(t[j] == '\0') return i-j; // 匹配成功,返回下标 else return 0; } int main() { // 测试strLength char str1[] = "Hello"; cout << "Length of '" << str1 << "' is: " << strLength(str1) << endl; // 测试strCincat char str2[] = "World"; char result[50]; strCincat(str1, str2, result); cout << "Concatenation of '" << str1 << "' and '" << str2 << "' is: " << result << endl; // 测试strsub char subStr[50]; if(strsub(subStr, str1, 2, 3)) { cout << "Substring from position 2 with length 3: " << subStr << endl; } else { cout << "Invalid substring parameters." << endl; } // 测试strComp char str3[] = "Hello"; char str4[] = "Hello"; cout << "Comparison of '" << str3 << "' and '" << str4 << "': " << strComp(str3, str4) << endl; char str5[] = "Hello"; char str6[] = "World"; cout << "Comparison of '" << str5 << "' and '" << str6 << "': " << strComp(str5, str6) << endl; // 测试strFind char str7[] = "Hello World"; char str8[] = "World"; int index = strFind(str7, str8); if(index) { cout << "Found substring '" << str8 << "' in '" << str7 << "' at position: " << index << endl; } else { cout << "Substring not found." << endl; } return 0;}