当前位置: 代码迷 >> J2SE >> 请教这个方法如何写啊
  详细解决方案

请教这个方法如何写啊

热度:103   发布时间:2016-04-23 20:35:06.0
请问这个方法怎么写啊?
我有个如下的字符串

Flanked by climate change campaigner and former US vice-president Al Gore, Mr Palmer announced his party would vote against the Government's bid to abolish the Clean Energy Finance Corporation, the Renewable Energy Target and the Climate Change Authority.

我通过一个方法想把它自动转成:
A Flanked by climate change campaigner
B and former US vice-president Al Gore, Mr 
C Palmer announced his party would vote 
D against the Government's bid to abolish 
E the Clean Energy Finance Corporation,
F the Renewable Energy Target and the 
G Climate Change Authority.

要求
1.每行长度不超过40
2.开头有按照字母顺序的排序

谢谢!
------解决方案--------------------
	public static void main(String[] args) {
String input = "Flanked by climate change campaigner and former US vice-president Al Gore, Mr Palmer announced his party would vote against the Government's bid to abolish the Clean Energy Finance Corporation, the Renewable Energy Target and the Climate Change Authority.";
final int MAX_COUNT = 40;
ArrayList<String> array = new ArrayList<String>();
int beginIndex = 0, endIndex = 0, count = 0;
char LineNumber = 'A';
for(int i=0;i<input.length();i++){
if(input.charAt(i)==' '){
endIndex = i;
}
count++;
if(count>=MAX_COUNT){
if(i+1<input.length() && input.charAt(i+1)==' '){
endIndex = i+1;
}
array.add(LineNumber+" "+input.substring(beginIndex, endIndex));
LineNumber++;
beginIndex=endIndex+1;
count = i-endIndex;
}
}
if(endIndex<input.length()){
array.add(LineNumber+" "+input.substring(beginIndex));
}
for(String value : array){
System.out.println(value);
}
}

------解决方案--------------------
class AddBigChar
{
public static void main(String[] args) 
{
String str = "Flanked by climate change campaigner and former US vice-president Al Gore, Mr Palmer announced his party would vote against the Government's bid to abolish the Clean Energy Finance Corporation, the Renewable Energy Target and the Climate Change Authority.";
int length = 38;
StringBuilder sb = new StringBuilder();
for(int i=0; i<str.length()/length+1; i++){
if(i==0){
sb.append(((char)(65+i))+" "+new String(str.substring(0,length-1))+"\n");
} else if(i==(str.length()/length)) {
sb.append(((char)(65+i))+" "+new String(str.substring(i*length-1, str.length()-1))+"\n");
} else {
sb.append(((char)(65+i))+" "+new String(str.substring(i*length-1, (i+1)*length-1)+"\n"));
}
}
System.out.println(sb.toString());
}
}
  相关解决方案