image-20241109012448035

思路

我们不优先使用库函数

首先我们先考虑前后空格

去除空格

image-20241109115528622

让left向前走,right向后走,走到不是空格就好了,最后把剩下的存入到新数组里

1
2
3
4
5
6
7
8
9
10
11
12
13
char *removeKong(char *s){
int left=0;
int right=strlen(s)-1;
while(s[left++]==' ');
while(s[right++]==' ');
int new_length = right - left + 1;
char *sb = (char *)malloc(new_length + 1);
for(int i=0;i<right-left+1;i++){
sb[i]=s[left++];
}
sb[left]='\0';
return sb;
}

然后是去除中间多的空格

1
2
3
4
5
6
7
8
9
10
11
12
在上面的代码中,添加一个条件判断
while (left<=right){
if(s[left]!=' '){
sb[i++]=s[left];
x=0;
}
else if(x==0){
sb[i++]=' ';
x=1;
}
left++;
}

合起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
char *removeKong(char *s){
int left=0;
int right=strlen(s)-1;
while(s[left]==' '){
left++;
}
while(s[right]==' '){
right--;
}
int new_length = right - left + 1;
char *sb = (char *)malloc(new_length + 1);
int i=0;
int x=0;
while (left<=right){
if(s[left]!=' '){
sb[i++]=s[left];
x=0;
}
else if(x==0){
sb[i++]=' ';
x=1;
}
left++;
}
sb[i]='\0';
return sb;
}

反转字符串

接下来我们可以先反转字符串,再反转字符串中每个单词

先写一个反转字符串的代码

1
2
3
4
5
6
7
8
9
void reverseString(char *s,int left,int right){
while(left<right){
char temp=s[left];
s[left]=s[right];
s[right]=temp;
left++;
right--;
}
}

最终代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
void reverseString(char *s,int left,int right){
while(left<right){
char temp=s[left];
s[left]=s[right];
s[right]=temp;
left++;
right--;
}
}


char *removeKong(char *s){
int left=0;
int right=strlen(s)-1;
while(s[left]==' '){
left++;
}
while(s[right]==' '){
right--;
}
int new_length = right - left + 1;
char *sb = (char *)malloc(new_length + 1);
int i=0;
int x=0;
while (left<=right){
if(s[left]!=' '){
sb[i++]=s[left];
x=0;
}
else if(x==0){
sb[i++]=' ';
x=1;
}
left++;
}
sb[i]='\0';
return sb;
}

char* reverseWords(char* s) {
char* new_S=removeKong(s);
int len=strlen(new_S);
reverseString(new_S,0,len-1);
int left=0,right=0;
while(left<len){
while(right<len&& new_S[right]!=' '){
right+=1;
}
reverseString(new_S,left,right-1);
right++;
left=right;
}
return new_S;
}