用c语言编写一个程序表示字符串的基本操作,包括求串长、赋值、比较、串连接、求子串、替换和定位算法
时间: 2024-01-14 17:02:29 浏览: 69
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 求串长
int strLength(char* str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
// 赋值
void strAssign(char* dst, char* src) {
while (*src != '\0') {
*dst = *src;
dst++;
src++;
}
*dst = '\0';
}
// 比较
int strCompare(char* str1, char* str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 > *str2) {
return 1;
} else if (*str1 < *str2) {
return -1;
}
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0') {
return 0;
} else if (*str1 == '\0') {
return -1;
} else {
return 1;
}
}
// 串连接
void strConcat(char* dst, char* str1, char* str2) {
while (*str1 != '\0') {
*dst = *str1;
dst++;
str1++;
}
while (*str2 != '\0') {
*dst = *str2;
dst++;
str2++;
}
*dst = '\0';
}
// 求子串
void substr(char* dst, char* src, int start, int len) {
int i;
for (i = 0; i < len; i++) {
dst[i] = src[start + i];
}
dst[len] = '\0';
}
// 替换
void strReplace(char* dst, char* src, char* oldStr, char* newStr) {
int oldLen = strlen(oldStr);
int newLen = strlen(newStr);
while (*src != '\0') {
if (strstr(src, oldStr) == src) {
strcpy(dst, newStr);
dst += newLen;
src += oldLen;
} else {
*dst = *src;
dst++;
src++;
}
}
*dst = '\0';
}
// 定位算法
int strIndex(char* str, char* subStr) {
char* p = str;
char* q = subStr;
while (*p != '\0' && *q != '\0') {
if (*p == *q) {
p++;
q++;
} else {
p = p - q + 1;
q = subStr;
}
}
if (*q == '\0') {
return p - str - strlen(subStr) + 1;
} else {
return -1;
}
}
int main() {
char str1[100] = "hello";
char str2[100] = "world";
char str3[100] = "hello";
char str4[100] = "world";
char str5[100] = "hello";
char str6[100] = "world";
char str7[100] = "hello, world";
char str8[100] = "world";
char str9[100] = "hello, world";
char str10[100] = "world";
char str11[100] = "hello, world";
char str12[100] = "world";
char str13[100] = "hello, world";
char str14[100] = "world";
char str15[100] = "hello, world";
char str16[100] = "world";
char str17[100] = "hello, world";
char str18[100] = "world";
char str19[100] = "hello, world";
char str20[100] = "world";
printf("str1 length: %d\n", strLength(str1));
strAssign(str2, str1);
printf("str2: %s\n", str2);
printf("str1 compare str3: %d\n", strCompare(str1, str3));
strConcat(str4, str1, str2);
printf("str4: %s\n", str4);
substr(str5, str1, 1, 3);
printf("str5: %s\n", str5);
strReplace(str6, str7, str8, str9);
printf("str6: %s\n", str6);
int index = strIndex(str11, str12);
printf("str12 index in str11: %d\n", index);
return 0;
}
```
阅读全文