C#中如何按字节数截取字符串字节数

请教,如何按字节长度截取字符串??
[问题点数:60分,结帖人zhao8954]
请教,如何按字节长度截取字符串??
[问题点数:60分,结帖人zhao8954]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
2010年11月 总版技术专家分月排行榜第二2010年9月 总版技术专家分月排行榜第二2010年8月 总版技术专家分月排行榜第二
2010年7月 总版技术专家分月排行榜第三
2010年 总版技术专家分年内排行榜第一2009年 总版技术专家分年内排行榜第一
2011年 总版技术专家分年内排行榜第二
匿名用户不能发表回复!|随笔 - 46&
文章 - 4&评论 - 1&trackbacks - 0
System.Text.Encoding.Default.GetByteCount("博客").ToString();
阅读(...) 评论()&>&超实用c#按字节截取长度(原创)
超实用c#按字节截取长度(原创)
上传大小:2KB
当字符串全部为单字节字符时,则可以用SubString方法截取指定长度即可。
当字符串全部为双字节字符时,则只需要用SubString方法截取指定长度的一半
当字符串为单字节双字节混合时,则我们可以用折中这样的方法来处理。
例如我们有一个长度为350字节的字符串。而我们需要截取100个字节,则我们进行如下操作:
先用SubString 方式取得100/2个字符。然后获取这50个字符的字节数。
当50个字符=100个字节时,则直接返回结果。如果还不到100个字节,则继续用SubString方法截取 (100-(50个字符的字节数))/2 的字符。如此循环直到剩下的字节数为1 或者0的时候,则停止。当剩余一个字节时,再进行判断下一个字符是否是单字节字符,如果是单字节,则把这个字符一起做为结果返回。如果双字节字符,则将下一个字符放弃,直接返回已经截取的字符串的长度。
用此方法为指数形式截取,一般截取长字符串时只需进行几步操作即可。
比如截取10000个字符,则进行最多12+1次操作即可
综合评分:3
{%username%}回复{%com_username%}{%time%}\
/*点击出现回复框*/
$(".respond_btn").on("click", function (e) {
$(this).parents(".rightLi").children(".respond_box").show();
e.stopPropagation();
$(".cancel_res").on("click", function (e) {
$(this).parents(".res_b").siblings(".res_area").val("");
$(this).parents(".respond_box").hide();
e.stopPropagation();
/*删除评论*/
$(".del_comment_c").on("click", function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_invalid/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parents(".conLi").remove();
alert(data.msg);
$(".res_btn").click(function (e) {
var parentWrap = $(this).parents(".respond_box"),
q = parentWrap.find(".form1").serializeArray(),
resStr = $.trim(parentWrap.find(".res_area_r").val());
console.log(q);
//var res_area_r = $.trim($(".res_area_r").val());
if (resStr == '') {
$(".res_text").css({color: "red"});
$.post("/index.php/comment/do_comment_reply/", q,
function (data) {
if (data.succ == 1) {
var $target,
evt = e || window.
$target = $(evt.target || evt.srcElement);
var $dd = $target.parents('dd');
var $wrapReply = $dd.find('.respond_box');
console.log($wrapReply);
//var mess = $(".res_area_r").val();
var mess = resS
var str = str.replace(/{%header%}/g, data.header)
.replace(/{%href%}/g, 'http://' + window.location.host + '/user/' + data.username)
.replace(/{%username%}/g, data.username)
.replace(/{%com_username%}/g, data.com_username)
.replace(/{%time%}/g, data.time)
.replace(/{%id%}/g, data.id)
.replace(/{%mess%}/g, mess);
$dd.after(str);
$(".respond_box").hide();
$(".res_area_r").val("");
$(".res_area").val("");
$wrapReply.hide();
alert(data.msg);
}, "json");
/*删除回复*/
$(".rightLi").on("click", '.del_comment_r', function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_comment_del/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parent().parent().parent().parent().parent().remove();
$(e.target).parents('.res_list').remove()
alert(data.msg);
//填充回复
function KeyP(v) {
var parentWrap = $(v).parents(".respond_box");
parentWrap.find(".res_area_r").val($.trim(parentWrap.find(".res_area").val()));
评论共有8条
不能去任意的长度,比如取4~12个单字节
不错,很好用。
用过好多次了,每次还是需要找代码,总是记不住。
VIP会员动态
CSDN下载频道资源及相关规则调整公告V11.10
下载频道用户反馈专区
下载频道积分规则调整V1710.18
spring mvc+mybatis+mysql+maven+bootstrap 整合实现增删查改简单实例.zip
资源所需积分/C币
当前拥有积分
当前拥有C币
输入下载码
为了良好体验,不建议使用迅雷下载
超实用c#按字节截取长度(原创)
会员到期时间:
剩余下载个数:
剩余积分:0
为了良好体验,不建议使用迅雷下载
积分不足!
资源所需积分/C币
当前拥有积分
您可以选择
程序员的必选
绿色安全资源
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
您的积分不足,将扣除 10 C币
为了良好体验,不建议使用迅雷下载
无法举报自己的资源
你当前的下载分为234。
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可返还被扣除的积分
被举报人:
举报的资源分:
请选择类型
资源无法下载 ( 404页面、下载失败、资源本身问题)
资源无法使用 (文件损坏、内容缺失、题文不符)
侵犯版权资源 (侵犯公司或个人版权)
虚假资源 (恶意欺诈、刷分资源)
含色情、危害国家安全内容
含广告、木马病毒资源
*详细原因:
超实用c#按字节截取长度(原创)博客分类:
碰到可能会截取汉字的情况,当然是要不能截取出乱码来,就是不能对整个汉字截取一半。如"我ABC汉字d"这个字符串,截取5个字节的时候,应该是"我ABC",而截取8个字节的时候,应该是"我ABC汉",而不应该是"我ABC汉?",其中"?"为半个汉字,可理解为向前截取
public static String subStr(String str, int subSLength)
throws UnsupportedEncodingException{
if (str == null)
return "";
int tempSubLength = subSL//截取字节数
String subStr = str.substring(0, str.length()&subSLength ? str.length() : subSLength);//截取的子串
int subStrByetsL = subStr.getBytes("GBK").//截取子串的字节长度
//int subStrByetsL = subStr.getBytes().//截取子串的字节长度
// 说明截取的字符串中包含有汉字
while (subStrByetsL & tempSubLength){
int subSLengthTemp = --subSL
subStr = str.substring(0, subSLengthTemp&str.length() ? str.length() : subSLengthTemp);
subStrByetsL = subStr.getBytes("GBK").
//subStrByetsL = subStr.getBytes().
return subS
备注:将字符编码GBK改为UTF-8,则每个中文长度按3个字符计算
以下方法是向后截取字符串
public static String subStr_1(String str, int start, int end)
throws UnsupportedEncodingException{
if (str == null)
String chinese = "[\u0391-\uFFE5]";
byte[] b = str.getBytes("UTF-8");
String temp = new String(b, start, end);
String last = getLastStr(temp);
while(!last.matches(chinese)){
temp = new String(b, start, ++end);
last = getLastStr(temp);
return new String(b, start, end);
public static String getByteStr(String str, int start, int end) throws UnsupportedEncodingException{
byte[] b = str.getBytes("UTF-8");
return new String(b, start, end);
以下代码会出现半个汉字问题
/**
* ReadFileByteBuffer.java
* cn.com.songjy.test.io
* Function: TODO
* ──────────────────────────────────
* Copyright (c) 2013, TNT All Rights Reserved.
package cn.com.songjy.test.
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.IOE
import java.nio.ByteB
import java.nio.CharB
import java.nio.channels.FileC
import java.nio.charset.C
import java.nio.charset.CharsetD
import org.apache.commons.logging.L
import org.apache.commons.logging.LogF
* ClassName:ReadFileByteBuffer
* @version
下午12:15:21
public class ReadFileByteBuffer {
private static Log log = LogFactory.getLog(ReadFileByteBuffer.class);
public static void main(String[] args) {
FileInputStream fis = new FileInputStream("pom.xml");/*创建文件输入流*/
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(64);//每次取出64字节
/*将FileChannel中的数据放入ByteBuffer*/
while(-1 != fc.read(bb)){
bb.flip();/*锁定ByteBuffer的空白区*/
Charset charset = Charset.forName("UTF-8");/*创建Charset对象*/
CharsetDecoder decoder = charset.newDecoder();/*创建解码器(CharsetDecoder)对象*/
CharBuffer cb = decoder.decode(bb);/*将ByteBuffer的内容转码*/
log.info(cb);
bb.clear();
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
/*会出现java.nio.charset.MalformedInputException错误,原因是“半个中文问题”*/
浏览 22892
浏览: 962864 次
来自: 江西
牛逼,正解!
[i][b][u]引用[list]
[*][img][flas ...
宋建勇 写道 写道&!-- 文件拷贝时 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(1354)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_094071',
blogTitle:'\t\tjs C# 求字符串 字节长度 截取字符串',
blogAbstract:'/*求出字节长度*/String.prototype.byteLen = function(len) { if (!this) { return \'\'; } var a = 0, b = 0, i = 0, temp = \'\'; for (i = 0; i & this. i++) { a += this.charCodeAt(i) & 255 ? 2 : 1; if (len) { if (a & len && b & len - 1) { return temp + &..&; } if (this.charCodeAt(i) & 32) { temp += this.charAt(i); b += this.charCodeAt(i) & 255 ? 2 : 1; } } } return len ? this : }',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:8,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}

我要回帖

更多关于 字符串根据字节数截取 的文章

 

随机推荐