姓名:王鸿刚 班级:11512 学号:20113051201
一实验题目
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
1.把每个单词的首字母变为大写。
2.把数字与字母之间用下划线字符(_)分开,使得更清晰
3.把单词中间有多个空格的调整为1个空格。
例如:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me What Cpp_2005_program
用户输入:
this is a 99cat
则程序输出:
This Is A 99_cat
我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。每个单词间由1个或多个空格分隔。
假设用户输入的串长度不超过200个字符。
二实验步骤:
(1)代码:
package com.soft.test;
public class test2
{
public static void main(String[] args)
{
String a="you and me what cpp2005program";
a="this is a 99cat";
a=a.trim();
a=(char) (a.charAt(0) - 32) + a.substring(1);
a=a.replaceAll("\\\\s+", " ");
for (int i = 0; i < a.length() - 1; i++)
{
if (a.charAt(i) == ' '
&& (a.charAt(i + 1) >= 'a' && a.charAt(i + 1) <= 'z'))
{
a = a.substring(0, i + 1) + (char) (a.charAt(i + 1) - 32)
+ a.substring(i + 2);
}
else if (((a.charAt(i) >= 'a' && a.charAt(i) <= 'z') || (a
.charAt(i) >= 'A' && a.charAt(i) <= 'Z'))
&& ((a.charAt(i + 1) >= '0' && a.charAt(i + 1) <= '9'))
|| ((a.charAt(i + 1) >= 'a' && a.charAt(i + 1) <= 'z') || (a
.charAt(i + 1) >= 'A' && a.charAt(i + 1) <= 'Z'))
&& ((a.charAt(i) >= '0' && a.charAt(i) <= '9')))
{
a = a.substring(0, i + 1) + "_" + a.substring(i + 1);
}
}
System.out.println(a);
}
}
(2)截图:
三实验总结:
在字符串的数组实验中应该掌握字符串常量和字符串函数特别是replaceall函数和charAt函数的使用。静态string类字符串中,一定要将使用各种操作方法处理后的字符串复制给其他的字符串。而动态的StringBuffer中直接复制个原字符串,而原字符串将被覆盖,工程中不需要辅组字符串。