编程题一:
格式化字符串,规则去除字符串头尾的空格字符,两个单词中间的空格字符只保留一个,要求不增加额外的空间,举例:字符串" 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
本文介绍了使用Java语言解决字符串格式化问题的方法,包括去除字符串两端空格、减少单词间多余空格并优化输出。通过对比两种不同策略的实现效果,阐述了方法二在效率上的优势。

被折叠的 条评论
为什么被折叠?



