有时候我们想要把一些数据保存道数据库,但是由于数据过长,导致保存到数据库会导致一些问题。
因此我们一般都会选择将字符串截取成一些较短的字符串。为了方便一些需要的同学,也为了记录
自己的学习过程,便自己简单写了一个截取字符串的工具类。仅仅为提供一些参考。<span style="font-size:14px;"></pre></h2><h1><pre name="code" class="java">package com.liao.utils;
import java.util.ArrayList;
import java.util.List;
public class StringUtils {
/**
* 给定一个长字符串内容,返回一个数组
*
* @param content
* 所有的内容
* @param count
* 需要每段截取的长度
* @return 所有分段的数组list
*/
public static List<String> getListFromContent(String content, int count) {
List<String> list = new ArrayList<String>();
// 获取String的总长度
int contentLength = content.length();
if (contentLength < count) {
list.add(content);
} else {
int begin = 0;
// 获取需要切割多少段
int cutCount = contentLength / count;
int cutCounts = contentLength % count;
// 获取切割段的长度
if (cutCounts != 0) {
cutCount++;
}
for (int i = 1; i <= cutCount; i++) {
String temp;
// 不是最后一段
if (i != cutCount) {
temp = content.substring(begin, count * i);
} else {
temp = content.substring(begin, contentLength);
}
begin = count * i;
list.add(temp);
}
}
return list;
}
}</span>
<span style="font-size:14px;"></pre></h2><h1><pre name="code" class="java">package com.liao.utils;
import java.util.ArrayList;
import java.util.List;
public class StringUtils {
/**
* 给定一个长字符串内容,返回一个数组
*
* @param content
* 所有的内容
* @param count
* 需要每段截取的长度
* @return 所有分段的数组list
*/
public static List<String> getListFromContent(String content, int count) {
List<String> list = new ArrayList<String>();
// 获取String的总长度
int contentLength = content.length();
if (contentLength < count) {
list.add(content);
} else {
int begin = 0;
// 获取需要切割多少段
int cutCount = contentLength / count;
int cutCounts = contentLength % count;
// 获取切割段的长度
if (cutCounts != 0) {
cutCount++;
}
for (int i = 1; i <= cutCount; i++) {
String temp;
// 不是最后一段
if (i != cutCount) {
temp = content.substring(begin, count * i);
} else {
temp = content.substring(begin, contentLength);
}
begin = count * i;
list.add(temp);
}
}
return list;
}
}</span>