在字符串指定字符位置处插入新字符

有时候生成txt文件,会一不小心忘了加换行,导致所有item都在一行,但希望每个item在独立地一行。每个item的字符串都是满足一定的特点的,因而可以通过插入'\n'的方法作修改。

比如,有一文件“1.txt”的内容是“word_1.png,Latinword_2.png,Latinword_3.png,Latinword_4.png,Latinword_5.png,Latin”,只有一行。那么就这样去改:

import re

with open("1.txt",'r') as f:
    s = f.readlines()    # 注意这是一个列表
    s_list = list(s[0])    # 字符串转化为列表,便于插入
    loc = [here.start() for here in re.finditer('word', s[0])]    # 寻找匹配的位置
    loc = loc[1:]
    loc.reverse()    # 很重要!如果从前向后插入的话,后面的位置序号会因前面的先插入而被打乱
    for idx in iter(loc):
        s_list.insert(idx, '\n')    # 插入字符(这里是换行)
    s1 = ''.join(s_list)    # 从列表转化为字符串

with open("1.txt",'w') as f:
    f.writelines(s1)    # 存储结果

这样就得到了

word_1.png,Latin
word_2.png,Latin
word_3.png,Latin
word_4.png,Latin
word_5.png,Latin

### C语言字符串指定位置插入字符串 在C语言中,由于字符串是以字符数组的形式存在,并且以空字符 `\0` 结尾,所以要在某个特定的位置插入字符串并不是件直接的事情。通常的做法是先分配足够的空间给目标字符串以便容纳加入的内容,再移动原有数据腾出插入的空间,最后复制要插入的子字符串。 下面展示段用于实现在已有的字符串 `destStr` 的第 `pos` 位之前插入的子字符串 `insertStr` 的代码: ```c #include <stdio.h> #include <string.h> void insert_substring(char *dest, int pos, const char *insert) { size_t dest_len = strlen(dest); size_t ins_len = strlen(insert); // Check if position is valid and within the bounds of destination string. if (pos > dest_len || pos < 0) { printf("Invalid insertion position.\n"); return; } // Allocate memory for new string with enough space to hold both strings plus null terminator. char *new_str = malloc(strlen(dest) + strlen(insert) + 1); if (!new_str) { // If allocation fails perror("Failed to allocate memory."); return; } // Copy part before insertion point into new string strncpy(new_str, dest, pos); // Append inserted string at specified location strcpy(new_str + pos, insert); // Finish by appending rest of original string after insertion strcat(new_str + pos + ins_len, dest + pos); // Print result or use it as needed; here we just demonstrate printing puts(new_str); free(new_str); // Don't forget to release allocated memory when done using it } int main() { char str[] = "HelloWorld"; const char* sub = ", "; insert_substring(str, 5, sub); // Inserting a comma followed by space between Hello and World return 0; } ``` 上述代码实现了在个已有字符串中的任意合法位置插入的子字符串的功能[^1]。需要注意的是,在实际应用此函数时应当考虑边界条件以及内存管理等问题,比如当输入参数不合理时给出适当提示并安全退出操作;另外就是动态分配的内存要及时释放以免造成泄漏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值