例一:
- /*
- "abc ttt,kmd,uuu xyz"
- 用逗号或空格隔开字符串
- 分解为各个部分
- */
- public class T1
- {
- public static void main(String[] args)
- {
- String s = "abc ttt,kmd,uuu xyz";
- String s2 = "";
- // 一刀切 (上式: 事先补齐法)
- s = s + " ";
- for(int i=0; i<s.length(); i++){
- char c = s.charAt(i);
- if(c==' ' || c==','){
- System.out.println(s2);
- s2 = "";
- }
- else
- s2 = s2 + c;
- }
- }
- }
例二:
- /*
- "abcd" ==> "a,b,c,d"
- 每个字母间加逗号
- */
- public class T2
- {
- public static void main(String[] args)
- {
- String s = "abcd";
- String s2 = "";
- for(int i=0; i<s.length(); i++){
- s2 += "," + s.charAt(i);
- }
- // 一刀切 (下式: 事后修正法)
- System.out.println(s2.substring(1));
- }
- }
例三:
- /*编程
- 假设手机通话时间不会大于24小时。<=24
- 某个用户的开始通话时间为: 12:38:15
- 结束通话时间为: 12:39:16
- 则该用户通话时长为:62秒
- 对于一般的情况,可能需要考虑:跨分钟,跨小时,跨零点的问题。
- 如果已知了开始和结束时间,试编程求通话时长。
- 时间格式为:hh:mm:ss
- 小时采用24小时制
- 提示:关键在于如何处理,能把貌似不同的特殊情况转化为一致的普通情况。*/
- public class Homework5 {
- public static void main(String[] args) {
- String beg = "23:42:17";
- String end = "03:48:24";
- int time = talkTime(beg, end);
- if (time <= 60) {
- System.out.println("通话时间:" + "00:" + "00:" + time);
- }
- else if (time <= 60*60) {
- System.out.println("通话时间:" + "00:" + time/60 + ":" + time%60 );
- }
- else {
- System.out.println("通话时间:" + time/(60*60) + ":" + (time/60 - time/(60*60)*60)%60 + ":" + time%60 );
- }
- }
- private static int talkTime(String st1,String st2) {
- int time = toSce(st2) - toSce(st1) + 1;
- if (time < 0) {
- time = 24*60*60 + time;
- }
- return time;
- }
- private static int toSce(String st) {
- int hh = Integer.valueOf(st.substring(0, 2));
- int mm = Integer.valueOf(st.substring(3, 5));
- int ss = Integer.valueOf(st.substring(6, 8));
- int time = hh*60*60 + mm*60 + ss;
- return time;
- }
- }