蓝桥杯2014年以前JAVA历年真题及答案整理——串的简单处理

来源:互联网 发布:流畅的python 中文书评 编辑:程序博客网 时间:2024/06/05 06:32

串的处理

在实际的开发工作中,对字符串的处理是最常见的编程任务。

本题目即是要求程序对用户输入的字符串进行处理。具体规则如下:

1.  把每个单词的首字母变为大写。

2.  把数字与字母之间用下划线字符(_)分开,使得更清晰

3.  把单词中间有多个空格的调整为1个空格。

例如:

用户输入:

youand me what cpp2005program

则程序输出:

YouAnd Me What Cpp_2005_program

用户输入:

this is a 99cat

则程序输出:

ThisIs A 99_cat

我们假设:用户输入的串中只有小写字母,空格和数字,不含其它的字母或符号。

每个单词间由1个或多个空格分隔。

假设用户输入的串长度不超过200个字符。

import java.util.Scanner;import java.util.Vector;public class Main {//y j gpublic static void main(String[] args) {Scanner scanner = new Scanner (System.in);String string  = scanner.nextLine();Vector<Character> vector = new Vector<Character>();for (int i = 0 ; i <string.length() ; i ++){vector.add(string.charAt(i));}try{int index = 0 ; while(index < vector.size()){if(index==0&&vector.elementAt(index)>='a'&&vector.elementAt(index)<='z'){//首字母大写vector.set(index, (char)(vector.elementAt(index)-('a' - 'A')));}else if(vector.elementAt(index-1)==' '&&vector.elementAt(index)==' '){//除去多余空格vector.remove(index);index--;}else if (vector.elementAt(index-1)==' '&&(vector.elementAt(index)>='a'&&vector.elementAt(index)<='z')){//其它单词首字母大写vector.set(index,(char)(vector.elementAt(index)-('a' - 'A')));}else if((vector.elementAt(index)>='a'&&vector.elementAt(index)<='z')&&(vector.elementAt(index-1)>='0'&&vector.elementAt(index-1)<='9')){//数字字母间用"_"隔开vector.add(index,'_');index++;}else if((vector.elementAt(index-1)>='a'&&vector.elementAt(index-1)<='z')&&(vector.elementAt(index)>='0'&&vector.elementAt(index)<='9')){//字母数字间用“_”隔开vector.add(index,'_');index++;}index++;}for(int i = 0 ; i < vector.size() ; i++){System.out.print(vector.elementAt(i));}System.out.println();}catch(ArrayIndexOutOfBoundsException e){}}


0 0
原创粉丝点击