ITeye博客

常考的几个字符串截取题

qingBYqing · 2010-11-11 22:42 · Java · 编程语言 · J# · Markdown

[color=red]一。给定一串非连续的字符串(有空格),要求将其中连续的部分字符串中最长的一段找出来。 [/color] [code="java"] package com.qingbyqing.algorithm; import java.util.ArrayList; import java.util.List; public class StrigCut2 { /** * 1.将连续的字符串截取出来,放入队列中 */ static List getSequentialString(String str) { int begin = 0; List sequenList = new ArrayList(); // 首先将str中行首和行尾的空格去除 String st = str.trim(); for (int i = 0; i < st.length(); i++) { if (st.charAt(i) == ' ') { sequenList.add(st.substring(begin, i)); begin = i + 1; } } // 最后一串连续字符串的截取,并加入队列中 sequenList.add(st.substring(st.lastIndexOf(' ') + 1, st.length())); return sequenList; } /** * 2.将队列中的连续字符串,取出比较他们的长度,求出最长的连续的字符串 */ static int findMaxString(List sequenString) { int max = 0; for (int j = 0; j < sequenString.size(); j++) { if (max <= sequenString.get(j).length()) { max = sequenString.get(j).length(); } } return max; } /** * 测试 * * @param args */ public static void main(String[] args) { String str = "asf fjklasj kdfjalj jlsajl "; List sequenList = getSequentialString(str); int max = findMaxString(sequenList); // 找出 连续字符串,中最长的字符并打印 for (int i = 0; i < sequenList.size(); i++) { if (sequenList.get(i).length() == max) { System.out.println("最长连续字符串为:" + sequenList.get(i) + " 长度为:" + max); } } } } [/code]输出结果:最长连续字符串为:fjklasj 长度为:7 最长连续字符串为:kdfjalj 长度为:7 [color=red]二. 给定一字符串,按给定字节数截取字符串,如果有中文不能截取中文的一半,如:字符串“asf我vsba”,字节数:4 ;截取的结果为 :asf [/color] [code="java"] package com.qingbyqing.algorithm; import java.io.UnsupportedEncodingException; public class StringCut1 { /** *给定一个字符串,指定截取其中的字节数,如果有中文字符不能截取一半 * * @param s * :给定的字符串 * @param n * :指定截取的字节数 * @param encoding * :编码格式 * @return * @throws UnsupportedEncodingException */ static String getSubString(String s, int n, String encoding) throws UnsupportedEncodingException { int all = 0; // 如果给定的字符串是空,或者指定的字节数0,则返回null if (s.length() == 0 || n == 0) { return null; } // 创建一个StringBuilder用来存储截取的字符 StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { String tem = s.substring(i, i + 1); // 中文字符在GBK编码中式占2个字节在UTF-8编码中占3个字节 byte[] byteAll = tem.getBytes(encoding); // 获得所截字符的字节数 all += byteAll.length; // 截取的字符加入StringBuilder中 sb.append(tem); if(all==n){ return sb.toString(); } if (all-1 == n) {// 不能截取半个中文字符 break; } } return sb.toString(); } /** * 测试 * @param args * @throws UnsupportedEncodingException */ public static void main(String[] args) throws UnsupportedEncodingException{ String s="l我o爱v你e"; int n=5; String encoding="GBK"; String str = getSubString( s, n, encoding); System.out.println(str); } } [/code]输出结果:l我o爱

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。