按指定长度截取字符串

import java.util.ArrayList;
import java.util.List;
public class StringUtils {
/**
* 给定一个长字符串内容,返回一个数组
*
* @param content
* 所有的内容
* @param count
* 需要每段截取的长度
* @return 所有分段的数组list
/
public static List getListFromContent(String content, int count) {
List list = new ArrayList();
// 获取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;
}
}


作者:zhengxiang_liao
来源:CSDN
原文:https://blog.csdn.net/zhengxiang_liao/article/details/51454209

转载于:https://www.cnblogs.com/xiaoshen666/p/10772268.html

在 C# 中,按指定长度截取字符串是一种常见的需求。这可以通过多种方式实现,包括使用 `Substring` 方法、正则表达式或者自定义逻辑。以下是几种具体实现方案: ### 使用 Substring 方法 这是最直接也是最常见的方法之一。`Substring(int startIndex, int length)` 可以从给定索引位置提取具有特定长度的子字符串。 ```csharp public static string ExtractStringByLength(string source, int start, int length) { if (source == null || start >= source.Length) return ""; // 如果请求的长度超出范围,则仅返回剩余部分 if (start + length > source.Length) { length = source.Length - start; } return source.Substring(start, length); } ``` 上述代码展示了一个简单的封装函数[^1],它允许开发者轻松地依据起始点和期望长度来获取子串。 ### 自定义方法:考虑多字节字符的情况 当涉及到非 ASCII 字符集时(比如中文),仅仅依靠字符数量可能不足以准确表示占用的实际字节数量。因此有必要创建一个更加健壮的方法来处理这种情况: ```csharp /// <summary> /// 根据字节数裁剪字符串 /// </summary> /// <param name="input">原始字符串</param> /// <param name="byteCountLimit">限制的总字节数</param> /// <returns></returns> public static string TrimStringToByteSize(string input, int byteCountLimit) { if (!string.IsNullOrEmpty(input)) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; // 或者其他编码 byte[] allBytes = encoding.GetBytes(input.ToCharArray()); if(allBytes.Length <= byteCountLimit){ return input; } StringBuilder sbResult = new StringBuilder(); int currentByteSum = 0; foreach(char c in input){ byte[] charBytes = encoding.GetBytes(new[]{c}); if(currentByteSum + charBytes.Length > byteCountLimit){ break; } sbResult.Append(c); currentByteSum += charBytes.Length; } return sbResult.ToString(); } return ""; } ``` 这段代码提供了一种机制,用来计算每个字符所占的真实字节数,并据此决定何时停止追加新的字符到最终结果中去[^3]。 ### 利用 LINQ 实现复杂查询 虽然对于基本的任务来说有点大材小用了,但是借助强大的 Language Integrated Query (LINQ),我们也可以构建非常灵活且可读性强的解决方案。例如下面的例子演示了如何选取前 N 个字符组成新序列: ```csharp var result = String.Concat(yourOriginalString.Take(desiredNumberOfCharacters)); ``` 这种方式特别适合那些已经熟悉 LINQ 的程序员们快速解决问题[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值