Java String類練習題

題目:
1. 給定一個字符串,判斷該字符串中是否包含某個子串.若是包含,求出子串的全部出現位置.
如:"abcbcbabcb34bcbd"中,"bcb"子串的出現位置爲: 1,7,12.字符串和子串均由用戶輸入java

2.給定一個長度,隨機產生一個該長度的字符串,由大寫,小寫字母以及數字組成
Java中隨機數的生成:
java.util.Random r = new java.util.Random();
int a = r.nextInt(100): a 0-99的隨機數dom

3.給定一個由數字組成的字符串,如:"1239586838923173478943890234092",統計
出每一個數字出現的次數blog

答案以下:字符串

package Chp10;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class TestString2
{
	public static void Method_One()
	{
		
		Scanner s = new Scanner(System.in);
		System.out.println("請輸入一個父串");
		String str = s.next();
		
		System.out.println("請輸入一個子串");
		String str1 = s.next();
		
		int stat = 0;
		while (true)
		{
			int i = str.indexOf(str1,stat);
			if (i==-1)
			{
				break;
			}
			System.out.println(i);
			stat = i+str1.length();
		}
		
	}
	
	public static void Method_Two()
	{
		System.out.println("請輸入一個長度");
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		char[] cs = new char[n];
		
		Random random = new Random();
		for (int i = 0; i < n; i++)
		{
			int a = random.nextInt(62);
			if(a>=0 && a<=25)
			{
				a+=65;
			}
			else if (a>25 && a<=51) 
			{
				// 97 - 26 = 71
				a+=71;
			}
			else 
			{
				// 52-48 = 4
				a-=4;
			}
			cs[i] = (char)a;
		}
		System.out.println(cs);
	}
	
	public  static void  Method_Three()
	{
		Scanner scanner = new Scanner(System.in);
		String string = scanner.next();
		int[] c = new int[10];
		for (int i = 0; i < string.length(); i++)
		{
			char c1 = string.charAt(i); //48-57
			int a = c1-48;	// 類型轉換
			c[a]++;
		}
		for (int i = 0; i < c.length; i++)
		{
			System.out.println(i+" 出現的次數: "+c[i]);
		}
		
		System.out.println("=========方法二==========");
		String s = "12548954231351486214894562";
		char[] ch = s.toCharArray();
		
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		Set<Character> set = map.keySet();
		for (int i = 0; i < ch.length; i++)
		{
			if (set.contains(ch[i])) // 判斷map中已經有的char值
			{
				map.put(ch[i], map.get(ch[i])+1);
			} else
			{
				map.put(ch[i], 1); // 第一次放入map中
			}
		}
		Set<Character> set2 = map.keySet();
		for (Character character : set2)
		{
			System.out.println(character+"=========="+map.get(character));
		}
	}
	
	public static void main(String[] args)
	{
		System.out.println("第一題以下:");
		Method_One();
		System.out.println("第二題以下:");
		Method_Two();
		System.out.println("第三題以下:");
		Method_Three();
	}
}
相關文章
相關標籤/搜索