1. 程式人生 > >JAVA實現實現字元重複,用指定字元擴充字串,移除字串中的指定字元,字串反轉 不用直接反轉的方法

JAVA實現實現字元重複,用指定字元擴充字串,移除字串中的指定字元,字串反轉 不用直接反轉的方法

import java.util.Scanner;
public class StringsTest{
	

	public static void main(String[] args){
		
		//實現字元重複
		Scanner scanner = new Scanner(System.in);
		while(true){
		System.out.println("請輸入被重複字元 和 重複的次數");
		String c = scanner.next();
		char s = c.charAt(0);
		int  count = scanner.nextInt();
		if(count <= 0){
			System.out.println("輸入有誤,請輸入大於零的整數");
		}else{
			char[] x = new char[count];
		for(int i = 0;i<count;i++){
			x[i] = s;
			System.out.print(x[i]);
		    }
			break;
		}
		}    		
	}
	}
import java.util.Scanner;
public class StringsTest{
	

	public static void main(String[] args){
		
		   //用指定字元擴充字串
        Scanner sc = new Scanner(System.in);
		String str = "abc";//被填充前的原始字串
		System.out.println("請輸入填充的字元   and   字元個數");
		String c = sc.next();
		char s = c.charAt(0);
		int count = sc.nextInt();
		count = count - str.length();
		if(count>0){
		char[] x = new char[count];
		for(int i = 0;i<count;i++){
			x[i] = s;
		}
		String y = new String(x);
		System.out.println(str.concat(y));
		//String z = str.concat(y);
		}else{
			System.out.println(str);
		}     

	}
	}

import java.util.Scanner;
public class StringsTest{
	

	public static void main(String[] args){	
		//移除字串中的指定字元
		Scanner sc = new Scanner(System.in);
		String str = null;
		System.out.println("請輸入字串    and  要移除的字元");
		str = sc.next();
		String x = sc.next();
		char s = x.charAt(0);//保證輸入的是字元
		String ss = Character.toString(s);
		//百度找到了Character類的靜態方法 將輸入的字元型s 轉化為字串形式 
		//不然下面的字串替換方法 會報錯(char無法轉化為String)
		//String str3 = Character.toString(a);
		System.out.println(str.replaceAll(ss,""));
		
		
	}
	}

import java.util.Scanner;
public class StringsTest{
	

	public static void main(String[] args){
			
		//字串反轉  不用直接反轉的方法
		Scanner sc = new Scanner(System.in);
		System.out.println("請輸入要反轉的字串");
		String str = sc.next();
		int s = str.length();
		for(int i = s-1;i >= 0;i--){
			char redata = str.charAt(i);
			System.out.print(redata);
		}
		
	}
	}