`
20386053
  • 浏览: 434826 次
文章分类
社区版块
存档分类
最新评论

在java中对字符串的一些实现处理

 
阅读更多
package my.yaner;

public class StringTest {

	public static void main(String[] args) {
//		sentenceSplit();
		formatString(null, null);
	}

	
	/**
	 * 分割句子
	 * 功能:     在一个指定的控件中,能够显示的文字自适应到该控件里,
	 * 			如果当前显示不出该单词,则重新换行到下一行显示。
	 * 实现思路:
	 * 			将要显示的语句通过分割将所有单词放到一个数组中,
	 * 			然后循环取数组中的每个单词,如果当前句超过指定的
	 * 			字节数(假如一句就显示30个字节),则拼接“换行符\n”,
	 * 			开始新的一句,否则直接拼接从数组中读出的单词。
	 */
	private static void sentenceSplit(){
		String showContent = "i will go home, and i will work better than future, so now i will learn more somethings. oh ye!";		//要显示的文字
		String lastContent = "";	//拼接换行后的字符串
		int totalWidth = 60;		//每行能够显示的字节数
		int preWordWidth = 2;		//每个字节的宽度
		String[] wordArray  = null;
		wordArray = showContent.split(" ");
		int arrLen = wordArray.length - 1;
		
		String tempSentence = "";				//临时拼接的当前句子
		for(int i = 0; i <= arrLen; i++) {		
			String word = wordArray[i];
			String temp = tempSentence;		//保存拼接前的操作
			tempSentence += word;
			int lenW = tempSentence.length() * preWordWidth;
			if (lenW > totalWidth) {		//说明加上当前单词会超出边界,所以应当换行, 将该单词放到下一行中显示
				lastContent += temp;
				lastContent += "\n";
				
				tempSentence = word;
				tempSentence += " ";
			} else if (lenW == totalWidth) {
				lastContent += tempSentence;
				lastContent += "\n";
				
				tempSentence = "";
			} 
			else {
				tempSentence += " ";					//每个单词之间要保留一个空格
				if (i == arrLen)
					lastContent += tempSentence;
			}
		}
		System.out.println("lastSentence: ");
		System.out.print(lastContent);
	}
	
	
	/**
	 * 仿照字符串格式化的形式,将字符串和后面给出的参数拼接起来
	 * 如: 我的梦想是{0}, {1}是我最大的动力,  new String[]{dreamReal, 追求}
	 */
	private static void formatString(String src, String[] args){
		src = "我的梦想是{0}, {1}是我最大的动力.";
		args = new String[]{"dreamReal", "追求"};
		
		StringBuffer result = new StringBuffer();
		char[] chArr = src.toCharArray();
		int len = chArr.length;
		for(int i = 0; i < len; i++) {
//			System.out.println(i + " : " + chArr[i]);
			char ch = chArr[i];
			if(ch == '{') {
				ch = chArr[++i];
				StringBuffer sbNum = new StringBuffer();
				while(ch != '}') {
					sbNum.append(ch);
					++i;
					ch = chArr[i]; 
				}
				int num = Integer.parseInt(sbNum.toString());
				String arg = args[num];
				result.append(arg);
				continue;
//				System.out.println("提取出的参数为:" + sbNum);
			}
			result.append(ch);
		}
		System.out.println("组合后的字符串为:" + result.toString());
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics