·
编程学习 ·
97703
1 package FileDemo;
2
3 import java.io.IOException;
4
5 public class CutStringTest {
6
7 /**
8 * @param args
9 * @throws IOException
10 */
11 public static void main(String[] args) throws IOException {
12
13 String str = "ab你好cd谢谢";
14 /*byte buf[]=str.getBytes("GBK");
15 for(byte ch:buf){
16 System.out.println(Integer.toBinaryString(ch));
17 }*/
18 int len = str.getBytes("gbk").length;
19 for (int x = 0; x < len; x++) {
20 System.out.println("截取" + (x + 1) + "字节结果时:"
21 + cutStringByByte(str, x + 1));
22 }
23 String str1 = "ab你好cd杮";
24 int len1 = str.getBytes("gbk").length;
25 for (int x = 0; x < len1; x++) {
26 System.out.println("截取" + (x + 1) + "字节结果时:"
27 + cutStringByU8(str1, x + 1));
28 }
29 }
30
31 // 使用UTF-8编码表进行截取字符串,一个汉字对应三个负数,一个英文字符对应一个正数
32 private static String cutStringByU8(String str, int len) throws IOException {
33
34 byte[] buf = str.getBytes("utf-8");
35 int count = 0;
36 for (int x = len - 1; x >= 0; x--) {
37 if (buf[x] < 0) {
38 count++;
39 } else {
40 break;
41 }
42 }
43 if (count % 3 == 0) {
44 return new String(buf, 0, len, "utf-8");
45 } else if (count % 3 == 1) {
46 return new String(buf, 0, len - 1, "utf-8");
47 } else {
48 return new String(buf, 0, len - 2, "utf-8");
49 }
50 }
51
52 // 使用GBK编码表进行字符串的截取,一个英文字符对应码表一个正数,一个汉字对应两个负数
53 public static String cutStringByByte(String str, int len)
54 throws IOException {
55 byte[] buf = str.getBytes("gbk");
56 int count = 0;
57 for (int x = len - 1; x >= 0; x--) {
58 if (buf[x] < 0) {
59 count++;
60 } else {
61 break;
62 }
63 }
64 if (count % 2 == 0) {
65 return new String(buf, 0, len, "gbk");
66 } else {
67 return new String(buf, 0, len - 1, "gbk");
68 }
69 }
70
71 }
torch.nn.Embedding不适合实现正弦位置编码,因其引入可学习参数且无法保证公式结构;正确做法是手动向量化计算sin/cos编码并注册为buffer。 PyTorch中torch.nn.Embedding不适合直接实现正弦位置编码 正弦位置编码(SinusoidalPositionalE...
fuzzywuzzy在Pandas中用apply变慢,因其纯Python实现且apply逐行调用、无法向量化;默认process.extractOne还需遍历全部候选,导致万行以上CPU明显卡顿。 为什么fuzzywuzzy在Pandas中直接用apply会变慢? 因为fuzzywuzzy(现为ra...
+拼接在循环中特别慢,因字符串不可变,每次s=s+item都新建对象并复制全部内容,时间复杂度达O(n²),引发大量内存分配与垃圾回收;推荐用list.append()+''.join()降至O(n)。 为什么+拼接字符串在循环里特别慢? Python中的字符串是不可变对象,每次用+拼接都会创建新字...
不能直接用eval,因为它会执行任意Python表达式,包括危险操作如os.system;ast.literal_eval仅安全解析str、int、list等无副作用字面量,不支持函数调用或运算符,且对语法格式极其严格。 为什么不能直接用eval 因为eval会执行任意Python表达式,包括调用函...
推荐使用bytes.hex():Python3.5+原生方法,语义清晰、性能好,返回小写十六进制字符串;binascii.hexlify()返回bytes需decode,已非首选;注意输入必须为bytes类型,字符串需先用bytes.fromhex()解析。 直接用binascii.hexlify(...
strip()只清理字符串首尾指定字符,不处理中间部分,参数为字符集合而非子串;lstrip()和rstrip()分别专用于左端和右端清理;默认无参时移除所有Unicode空白字符。 strip为什么没去掉中间的字符 strip()只处理字符串首尾,完全不碰中间部分。这是它和replace()的根本...
Base64图片在HTML中以<imgsrc="data:image/xxx;base64,..."形式存在,需先校验src是否以data:image/开头且含;base64,再解码,注意MIME类型匹配、padding补全及SVG文本写入。 Base64图片在HTML中长...
本文介绍一种纯Python内置方法,无需导入re模块,即可将长字符串按指定关键词(如"shiftdate")切分为多个子串,并确保每个子串以该关键词开头。核心思路是利用str.split()配合字符串拼接,精准保留分隔符。 本文介绍一种纯python内置方法,无需导入`re`模块,即可将长字符串按指...