String类中常用方法,数字的输入

1、字符串与字符数组的转换

a) Char c[] = str.toCharArray();

b) String str2 = new String(c);

c) String str3 = new String(c,0,3);//取出部分字符串变为String

2、取出字符串中指定位置的字符

a) Char c = str.charAt(index);

3、字符串变为byte数组

a) Byte b[] = str.getByte();

b) String str1 = new String(b);

c) String str2 = new String(b,0,3);

4、等到字符串的长度

str.lenght();注意此处调用的是方法,必须有()

5、查找自定的字符串是否存在;如果存在,返回位置,如果不存在,返回-1

a) str.indexOf(‘c’);

b) str.indexOf(‘c’,3);//从第四个开始查找。

6、去掉空格

a) str.trim();

7、字符串截取

a) str.substring(6);//从第七个开始截取

b) str.substring(0,5);//含头不含尾

8、按照指定的字符串拆分字符串

a) str.split(“a”);

9、字符串大小写转换

a) str.toUpperCase();

b) str.toLowerCase();

10、不区分大小写进行字符串比较

a) str1.equalsIgnoreCase(str2);

11、判断是否以指定字符串开头或者结尾

a) str.startsWith(“ad”);

b) str.endsWith(“cd”);

12、用指定的字符串替换

a) str.replaceAll(“ab”,”cd”);

 

习题:

1、翻转一个句子中的单词,比如 输入 this is a test  输出  test a is this;输入 foobar  输出 foobar

 1 package test01;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStreamReader;
 5 
 6 public class FanZhuan {
 7 
 8     public static void main(String[] args) {
 9         BufferedReader buf = null;
10         buf = new BufferedReader(new InputStreamReader(System.in));
11         String str = null;
12         System.out.println("请输入内容:");
13         try{
14             str = buf.readLine();
15         }catch(Exception e){
16             e.printStackTrace();
17         }
18         String[] st = str.split(" ");
19         for(int i=st.length-1;i>=0;i--){
20             System.out.print(st[i] + " ");
21         }
22     }
23 
24 }

 

数字的快速输入:

 1 package test01;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStreamReader;
 5 
 6 public class Matrix {
 7 
 8     public static void main(String[] args) {
 9         BufferedReader buf = null;
10         String[] str = new String[4];
11         for(int i=0;i<2;i++){
12             buf = new BufferedReader(new InputStreamReader(System.in));
13             try{
14                 str[i] = buf.readLine();
15             }catch(Exception e){
16                 e.printStackTrace();
17             }
18         }
19         System.out.println(str[0]);
20         String str0 = str[0].substring(1, 2);
21         int num = Integer.parseInt(str0);
22         System.out.println(num);
23     }
24 }

 

posted @ 2017-08-10 11:50  XuGuobao  阅读(906)  评论(0编辑  收藏  举报