---
title: "截取包含中、英文的字符串"
author: "skydove"
date: "2011-05-18T14:02:16Z"
tags: ["C", "C#", "C++"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-05-23T11:04:57Z"
id: 1048370
url: "https://skydove.iteye.com/blog/1048370"
---

```
// 用字节数组方法截取包含中、英文的字符串
	public static String splitStrByByte(String a, int length) {
		byte strs[] = a.getBytes();
		long count = 0;
		for (int i = 0; i < length; i++) {
			if (strs[i] < 0) {
				count++;
			}
		}

		// 如果有不完整的汉字，肯定是最后一个字符有问题
		int getLeng = count % 2 == 0 ? length : length - 1;

		return new String(strs, 0, getLeng);
	}

	// 用字符数组方法截取包含中、英文的字符串
	public static String splitStrByChar(String a, int length) {
		char strs[] = a.toCharArray();
		int charCount = 0;
		int temp = 0;
		for (char c : strs) {

			temp = temp + String.valueOf(c).getBytes().length;
			if (temp > length) {
				break;
			}
			charCount++;
		}

		return new String(strs, 0, charCount); // 注意这里：char数组，后面是字符数，而非byte数组的字节数
	}

	public static String splitStrByString(String src, int length) {
		
		byte [] strs = src.getBytes();
		String result = new String(strs, 0, length);

		if (!src.startsWith(result)) {
			result = new String(strs, 0, length - 1);
		}

		return result;
	}
```

 

 

以上3种方法都能达到按字节数截取字符串的目的

本机测试循环1万次，可以发现：

splitStrByByte耗时：94ms

splitStrByChar耗时：265ms ~ 281ms

splitStrByString耗时：141ms

可见第一种效率高点.