Skip to content

Commit 1d301de

Browse files
String 实现完成
1 parent 55f9b0a commit 1d301de

File tree

2 files changed

+58
-8
lines changed

2 files changed

+58
-8
lines changed

da-hua-shu-ju-jie-gou/05-string/README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,12 +150,38 @@ int Index(String S, String T, int pos) {
150150
return i;
151151
}
152152
Status Replace(String S, String T, String V) {
153+
int pos = Index(S, T, 1);
154+
int len = StrLength(T);
155+
if (pos) {
156+
StrDelete(S, pos, len);
157+
}
158+
StrInsert(S, pos, V);
153159
return OK;
154160
}
155161
Status StrInsert(String S, int pos, String T) {
162+
int len = StrLength(T);
163+
int strLen = StrLength(S);
164+
165+
for(int i=len; i>=0; i--) {
166+
int index = pos+i;
167+
if (index>strLen) {
168+
S[index] = T[i];
169+
continue;
170+
}
171+
S[index+len] = S[index];
172+
S[index] = T[i];
173+
}
174+
175+
S[0] = strLen+len;
156176
return OK;
157177
}
158178
Status StrDelete(String S, int pos, int len) {
179+
int strLen = StrLength(S);
180+
181+
for(int i=0; i<len; i++) {
182+
S[pos+i] = S[pos+len+i];
183+
}
184+
S[0] = strLen - len;
159185
return OK;
160186
}
161187
```

da-hua-shu-ju-jie-gou/05-string/string/string/String.c

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,14 @@ void StringTest(void) {
3838
int index = Index(s3, s2, 1);
3939
printf("SubString(%s, %s, %d): index: %d\n", s3, s2, 1, index);
4040

41+
status = StrDelete(s3, 8, 5);
42+
printf("StrDelete(%s, 8, 5)\n", s3);
4143

42-
// String s1 = c1;
43-
// String s2 = c2;
44-
//
45-
// printf("s1: %s\ns2: %s\n", s1, s2);
46-
//
47-
// int pos = Index(s1, s2, 0);
48-
// printf("Index: s1: %s, s2: %s, pos: %d\n",s1, s2, pos);
49-
//
44+
status = StrInsert(s3, 8, s2);
45+
printf("StrInsert(%s, 8, %s)\n", s3, s2);
5046

47+
status = Replace(s3, s2, s1);
48+
printf("Replace(%s, %s, %s)\n", s3, s2, s1);
5149
}
5250

5351

@@ -151,11 +149,37 @@ int Index(String S, String T, int pos) {
151149
return i;
152150
}
153151
Status Replace(String S, String T, String V) {
152+
int pos = Index(S, T, 1);
153+
int len = StrLength(T);
154+
if (pos) {
155+
StrDelete(S, pos, len);
156+
}
157+
StrInsert(S, pos, V);
154158
return OK;
155159
}
156160
Status StrInsert(String S, int pos, String T) {
161+
int len = StrLength(T);
162+
int strLen = StrLength(S);
163+
164+
for(int i=len; i>=0; i--) {
165+
int index = pos+i;
166+
if (index>strLen) {
167+
S[index] = T[i];
168+
continue;
169+
}
170+
S[index+len] = S[index];
171+
S[index] = T[i];
172+
}
173+
174+
S[0] = strLen+len;
157175
return OK;
158176
}
159177
Status StrDelete(String S, int pos, int len) {
178+
int strLen = StrLength(S);
179+
180+
for(int i=0; i<len; i++) {
181+
S[pos+i] = S[pos+len+i];
182+
}
183+
S[0] = strLen - len;
160184
return OK;
161185
}

0 commit comments

Comments
 (0)