c# string 字符串截取操作

	public static string SubStringByteWithPostfix(this string str, int len, string postfix) {
		if (str == null) return null;
		int bytes = 0;
		StringBuilder sb = new StringBuilder();
		char highSurrogate = '\0';
		foreach (var character in str) {
			if (char.IsHighSurrogate(character)) {
				highSurrogate = character;
				continue;
			}

			bool isLow = char.IsLowSurrogate(character);

			if (isLow || character > 0x7f) bytes += 2;
			else bytes += 1;

			if (bytes <= len) {
				if (isLow) sb.Append(highSurrogate);
				sb.Append(character);
				continue;
			}

			sb.Append(postfix);
			break;
		}
		return sb.ToString();
	}

留下评论

邮箱地址不会被公开。 必填项已用*标注