编程题一:
格式化字符串,规则去除字符串头尾的空格字符,两个单词中间的空格字符只保留一个,要求不增加额外的空间,举例:字符串" I am a little boy. ",经过格式化后为“I am a little boy.”
给定的C语言函数模型为public void formatString(char[] str, int length){}
我编写的java代码如下:
方法一:
public static void formatStringOne(char[] str, int length) {
boolean isWord = false;
int start = 0, end = 0, wordCount = 0;
for (int i = 0; i < length; i++) {
if (str[i] != ' ' && isWord == false) {
isWord = true;
start = i;
} else if (str[i] == ' ' && isWord == true) {
isWord = false;
end = i - 1;
if (wordCount > 0) {
System.out.print(' ');
}
for (int j = start; j <= end; j++) {
System.out.print(str[j]);
}
wordCount++;
}
}
}
方法二:
public static void formatStringTwo(char[] str, int length) {
boolean isWord = false;
int wordCount = 0;
for (int i = 0; i < length; i++) {
if (str[i] != ' ' && isWord == false) {
isWord = true;
if (wordCount > 0) {
System.out.print(' ');
}
wordCount++;
System.out.print(str[i]);
} else if (str[i] == ' ' && isWord == true) {
isWord = false;
} else if (str[i] != ' ' && isWord == true) {
System.out.print(str[i]);
}
}
}
其中方法二的效率比方法一高。
PS:这是我人生中的第一篇博客,欢迎大家拍砖吐槽!!
详细代码查看我的gihub