Java实现串的简单处理

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

  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个字符。

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static ArrayList<Character> list = new ArrayList<Character>();
    
    public void getResult(String A) {
        char[] arrayA = A.toCharArray();
        for(int i = 0;i < arrayA.length;i++) {
            if(arrayA[i] == ' ')
                continue;
            char temp = arrayA[i];
            if(temp >= '0' && temp <= '9') {
                list.add(temp);
            } else {
                 temp = (char) (temp - 32);
                list.add(temp);
            }
            if(i == arrayA.length - 1)
                break;
            temp = arrayA[++i];
            while(temp != ' ') {
                char t = arrayA[i - 1];
                if(t >= '0' && t <= '9' && temp >= 'a' && temp <= 'z')
                    list.add('_');
                else if(t >= 'a' && t <= 'z' && temp >= '0' && temp <= '9')
                    list.add('_');
                list.add(temp);
                if(i == arrayA.length - 1)
                    break;
                temp = arrayA[++i];
            }
            list.add(' ');
        }
        for(int i = 0;i < list.size();i++)
            System.out.print(list.get(i));
    }

    public static void main(String[] args) {  
        Main test = new Main();
        Scanner in = new Scanner(System.in);
        String A = in.nextLine();
        test.getResult(A);
    }  
}
posted @ 2019-07-26 22:28  南墙1  阅读(30)  评论(0编辑  收藏  举报