1. 程式人生 > >java實現-字串分割

java實現-字串分割

字串分隔
參與人數:33時間限制:1秒空間限制:32768K
通過比例:24.14%
最佳記錄:0 ms|8460K (來自  石青硃砂)
 演算法知識視訊講解
題目描述

•連續輸入字串,請按長度為8拆分每個字串後輸出到新的字串陣列; •長度不是8整數倍的字串請在後面補數字0,空字串不處理。
輸入描述:

連續輸入字串(輸入2次,每個字串長度小於100)


輸出描述:

輸出到長度為8的新字串陣列

輸入例子:

abc 123456789

輸出例子:

abc00000 12345678 90000000

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.stream.IntStream;

import javax.print.attribute.standard.PrinterLocation;

public class Main 
{
	public Main() 
	{
		// TODO Auto-generated constructor stub
	}

	public static void main(String[]args) throws FileNotFoundException
	{
		String line;
		StringBuffer stringBuffer;
		int pos=0;
		int length;
		int lineLength;
		
		Scanner scanner = new Scanner( new File("C://Users//Administrator//Desktop//test.txt"));
		while(scanner.hasNext())
	    {
	    	line = scanner.nextLine();
	    	stringBuffer = new StringBuffer();
	    	lineLength = line.length();
	    	for(int i =0;i<line.length();++i)
	    	{
	    		if(line.charAt(i)==' '||i == line.length()-1)
	    		{
	    			if(i+1<lineLength&&line.charAt(i+1)!=' ')
	    			{
	    				continue;
	    			}
	               length = i -pos;
	               if(length<8)
	               {
		               stringBuffer.append(line.substring(pos, i));
		               for(int j=length;j<8;++j)
		               {
		            	   stringBuffer.append("0");
		               }
		               pos=i+1;
	               }
	               else if( length>=8)
	               {
	            	   stringBuffer.append(line.substring(pos,i-(length-8)+1));
	            	   pos = i-(length-8)+1;
	            	   
	            	   if(i == lineLength-1)
	            	   {
	            		   stringBuffer.append(" ");
	            		   stringBuffer.append(line.substring(pos, i+1));
			               for(int j=i-pos;j<8;++j)
			               {
			            	   stringBuffer.append("0");
			               }
	            	   }
	               }
	           if(i!=lineLength-1)
	           {
	    		stringBuffer.append(" ");
	           }
	    		}
	    	    continue;	
	    	}
	    	System.out.println(stringBuffer.toString());
	    
	    }
	
	}



}