一、题目
原题链接Reverse words
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retaine
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
二、解题
1.关键:
1)空格长度非定常“1”,例子2中 空格长度就是2。
2)是否可能存在末尾空格,如“jfsa fsa sdfas ”。
3)如何保证字符串和空格串的相对位置不变,实现对应位置字符串倒序,空格位置与数量不变。(原题另类描述)
2、myway
此法关键:
1)用空格进行划分,将每块字符串连同其后空格,存入二维数组的一行,用"\0"封堵,便于后面长度读取。
2) 设置标志item,确保只有在读到空格后有读到新字符,才i++(创建二维数组新的一行)。
3)将char型数组中内容,加入指针*s:
(1)通过for循环读取每一行字符数组。
(2)第一个while,倒序读取第n行内容,先读入字符,通过“esle b--;”解决死循环。
(3)第二个while,再次倒序读取第n行内容,此次读取空格,通过“else break;”解决死循环。
(4)处理过程中,由于多次“s++;”使得最后,s地址处于末尾,故开始需另存s地址,用于返回。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* reverseWords(const char* text) {
char* s=(char *)malloc(sizeof(char)*(strlen(text)+2));
char *an=s;/*处理过程中,由于多次“s++;”使得最后,s地址处于末尾,古开始需另存s地址,用于返回。*/
char a[10][10];
int i=0,j=0,item=0;
while(*text!='\0'){
if(*text!=' '){
if(item==0){
a[i][j]=*text;
j++;
}
else{
a[i][j]='\0';/*封堵很关键,此处上下顺序不宜调换*/
text--;
item=0;
j=0;
i++;
}
}
else {
item=1;
a[i][j]=*text;
j++;
}
text++;
}
a[i][j]='\0';
int b,con;
for(int n=0;n<=i;n++){//通过for循环读取每一行字符数组。
printf("111111%s",a[n]);
b=strlen(a[n])-1;
con=b;
while(b>=0){/*第一个while,倒序读取第n行内容,先读入字符,通过“esle b--;”解决死循环。*/
if(a[n][b]!=' '){
*s=a[n][b];
s++;
b--;
}
else b--;
}
while(con>=0){/*第二个while,再次倒序读取第n行内容,此次读取空格,通过“else break;”解决死循环。*/
if(a[n][con]==' '){
*s=a[n][con];
con--;
s++;
}
else break;
}
}
printf("\n0000%s",an);
return an;
}
三、总结
1.循环需注意是否存在死循环,这很重要。
2.进行复制字符串的操作时,通过“\0”进行封堵,有时很重要。
3.处理问题换个思路,有时真的可以豁然开朗,大大降低问题难度。
4.申请动态地址时,需要强制类型转换;并且,为避免使用时地址越界,可适当增加申请的地址大小。
5.指针检测是否读到最后,印象中有*text!=NULL和*text!='\0',此处不太确定,留作探讨研究。
四、参考链接
编译错误:variable-sized object may not be initialized
以下思路未完成,无参考价值,是在编写时意识到将问题复杂化了,以此提醒以后可将问题简单化。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* p(char* q){
int s=strlen(q);
char item;
for(int i=0;i<s/2;i++){
item=q[i];
q[i]=q[s-1-i];
q[s-1-i]=item;
}
return q;
}
char* reverseWords(const char* text) {
char* s=(char *)malloc(sizeof(char)*strlen(text));
char a[20][20];
int i=0,j=0;
while(*text!='\0'){
if(*text!=' '){
a[i][j]=*text;
j++;
}
else {
a[i][j]=' ';
a[i][j+1]='\0';
i++;
j=0;
}
text++;
}
for(int n=0;n<=i;n++){
p(a[i]);
printf("%s",a[i]);
}
for(int n=0;n<=i;n++){
int w=strlen(a[i]);
if(a[w-1]==' '){
for(int u=w-2;u>=0;u--)
}
}
return s;
}