算法笔记_221:串的简单处理(Java)

目录

1 问题描述

2 解决方案

 


1 问题描述

串的处理
在实际的开发工作中,对字符串的处理是最常见的编程任务。本题目即是要求程序对用户输入的串进行处理。具体规则如下:
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个字符。


2 解决方案

 1 import java.util.ArrayList;
 2 import java.util.Scanner;
 3 
 4 public class Main {
 5     public static ArrayList<Character> list = new ArrayList<Character>();
 6     
 7     public void getResult(String A) {
 8         char[] arrayA = A.toCharArray();
 9         for(int i = 0;i < arrayA.length;i++) {
10             if(arrayA[i] == ' ')
11                 continue;
12             char temp = arrayA[i];
13             if(temp >= '0' && temp <= '9') {
14                 list.add(temp);
15             } else {
16                  temp = (char) (temp - 32);
17                 list.add(temp);
18             }
19             if(i == arrayA.length - 1)
20                 break;
21             temp = arrayA[++i];
22             while(temp != ' ') {
23                 char t = arrayA[i - 1];
24                 if(t >= '0' && t <= '9' && temp >= 'a' && temp <= 'z')
25                     list.add('_');
26                 else if(t >= 'a' && t <= 'z' && temp >= '0' && temp <= '9')
27                     list.add('_');
28                 list.add(temp);
29                 if(i == arrayA.length - 1)
30                     break;
31                 temp = arrayA[++i];
32             }
33             list.add(' ');
34         }
35         for(int i = 0;i < list.size();i++)
36             System.out.print(list.get(i));
37     }
38 
39     public static void main(String[] args) {  
40         Main test = new Main();
41         Scanner in = new Scanner(System.in);
42         String A = in.nextLine();
43         test.getResult(A);
44     }  
45 }

运行结果:

50cat do60     s1t2k30
50_cat Do_60 S_1_t_2_k_30 
原文地址:https://www.cnblogs.com/liuzhen1995/p/6893539.html