linux字符串处理

1. C 截取字符串,截取两个子串中间的字符串

linux

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void str_save_param(char * str,char left_str[],char right_str[],char result[]){
   char *ret = NULL;
   char *ret2;
   char *aaa = NULL;
   int left_str_len;

   //判断是否包含匹配字符串
   if( strstr(str, left_str)){
       //获取左边字符串的长度
       left_str_len = strlen(left_str);
       //获取匹配左边字符串
       ret = (char*) strstr(str, left_str);
       //删除掉左边字符串
       ret2 = (char *)malloc(strlen(ret));
       memset(ret2,0,sizeof(ret2));
       strcpy(ret2,ret+left_str_len);
       //lr_error_message("ret2字符串是 - |%s|\n", ret2);
       //获取右边匹配字符串
       aaa = (char*) strstr(ret2, right_str);
       if(aaa){
           memset(result,'\0',sizeof(result));
           //获取中间字符串
           strncpy(result, ret2, strlen(ret2) - strlen(aaa) );
           //lr_error_message("result字符串是 - |%s|\n", result);
       }
       free(ret2);
   } 
}

int main()
{
   char str[] = "=gfafgs/gafdbafd/a9999999jkhjhkjkkjjjnjf12\n\r";
   char left_str[] = "=";
   char right_str[] ="\r";
   char result[1024];

   str_save_param(str,left_str,right_str,result);

   printf("result......|   %s   |.......\n", result);

   return 0;
}

BUG
在这里插入图片描述
在这里插入图片描述

串口AT指令

// 截取字符串,截取两个子串中间的字符串
char g_str[400];
char* InterceptString (char *str, char *left_str, char *right_str)
{
	char *l_str = strstr(str, left_str);
	int r_str = strcspn(l_str, right_str);
	int l_len = strlen(left_str);
	int str_len = r_str - l_len;

	strncpy(g_str, l_str+l_len, str_len);
	g_str[str_len+1] = '\0';

	return g_str;
}


// 截取字符串的信号强度
  	char at[] = "AT+CSQ\r\n\r\n+CSQ: 18,99\r\n\r\nOK\r\n";
  	char *dd;
  	dd = InterceptString (at, "+CSQ: ",",99");
  	USART_printf(&huart1,"dd=%s\r\n",dd);//将串口2接收到的数据发送到串口1
  	memset(g_str, 0, sizeof(g_str));  // 清空字符串

2. 获取该字符串后面的字符串

用 strstr() 函数查找需要提取的特定字符串,然后通过指针运算获取该字符串后面的字符串

#include <stdio.h>
#include <string.h>
int main() {    
char str[] = "The quick brown fox jumps over the lazy dog";    
char *substr = strstr(str, "brown"); // 查找 "brown" 子串    
if (substr != NULL) 
{        
substr += strlen("brown"); // 获取 "brown" 后面的字符串        printf("%s", substr);    
}    
return 0;
}
#include <stdio.h>
#include <string.h>

char *get_str_spec(char *search_string, char *sing)
{
        char *substr = strstr(search_string, sing); // 查找 "search_string" 子串    
	if (substr != NULL) 
	{        
	    substr += strlen(sing); // 获取 "brown" 后面的字符串        printf("%s", substr);    
	}
	
	return substr;   
}

int main() {    
char str[] = "The quick brown fox jumps over the lazy dog";    
char *cCC=NULL;

cCC=get_str_spec(str, "brown ");
printf("%s\n",cCC);
}

输出结果为:

fox jumps over the lazy dog

用 strtok() 函数分割字符串,找到需要提取的特定字符串后,调用 strtok() 传入 NULL 参数继续分割字符串获取下一个子串。

#include <stdio.h>
#include <string.h>
int main() {    
char str[] = "The quick brown fox jumps over the lazy dog";    
char *token = strtok(str, " "); // 分割字符串,以空格为分隔符    
while (token != NULL) {        
if (strcmp(token, "brown") == 0) 
{ // 找到需要提取的特定字符串            
token = strtok(NULL, " "); // 继续分割字符串获取下一个子串            
 printf("%s", token);           
 break;       
  }        
token = strtok(NULL, " ");    }   
 return 0;
}

输出结果为:

fox

3. C语言strncpy

字符串的截取

#include <stdio.h>
#include <string.h>
 
int main(void){
  char dest[5]={0};
  char src[]="abcdefghijk";
 
  strncpy(dest,src,4);//注意一下这里假如改为5的话,可能会出现
                      //内存越界使得dest可能会占用其它模块的内存,从而导致错误发生;
  //strncpy(dest,src+5,4);//从第5个字符开始截取;
  printf("dest: %s\n",dest);
return 0;
}

从左边开始截取n个字符

static char* left(char *dest,const char *src ,int n){
char *p=dest;
char *q=src;
int len=strlen(src);
 
if(n>len){
  n=len;
}
while(n--) *(p++)=*(q++);
*(p++)='\0';
 
return dest;
} 

从右边开始截取n个字符

static char* light(char *dest,const char *src ,int n){
char *p=dest;
char *q=src;
int len=strlen(src);
 
if(n>len){
  n=len;
}
//int start=len-n;
//q=q+start;
q+=len-n;
while(n--) *(p++)=*(q++);
*(p++)='\0';
return dest;
} 

从中间某处截取一定长度的的子字符串

static char* cut_substr(char *dest,const char *src ,char start,int n){
char *p=dest;
char *q=src;
chsr *temp=NULL;
int len=strlen(src);
 
if(start>=len || start<0){
  return NULL;
}
temp=q+start;
if(n>strlen(temp)){//注意这里,截取长度如果超过了src剩余的长度则只截取到src的最后,以避免内存越界;
   n=strlen(temp);
}
q+=start;
while(n--) *(p++)=*(q++);
*(p++)='\0';
return dest;
} 

4.C语言中将文件中的某行的字符串读取出来

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MaxCols 2000     //设定每行字符数不超过MaxCols,根据变化调整 
//获取已经打开文件fp的第line行内容到stri,如果成功返回得到的字节数,
//如果没有那么多行,返回-2 
int getlinetxt(FILE *fp,int line,char *stri){
    int i;
    fseek(fp,0,0); //指针到文件最开始
    for(i=0;i<line;i++) 
        if(fgets(stri,MaxCols,fp)==NULL) //没有这么多行错误
            return -2;
   return strlen(stri);
}
//获取filename文件的第line行内容到stri,如果成功返回得到的字节数,
//如果打开文件失败,返回-1,如果没有那么多行,返回-2 
int getfiletxt(char *filename,int line,char *stri){
    FILE *fp;
    if ((fp=fopen(filename,"r"))==NULL){
        //打开文件错误,返回-1 
        return -1;
    }
    return getlinetxt(fp,line,stri);
    fclose(fp);
}
int main(){
    char s[MaxCols];
    int row=10, flag;
    //以下例子是获取d:\temp.txt的第10行文本内容 
    flag=getfiletxt("d:\\temp.txt",row,s);
    if (flag==-1)
        printf("打开文件错误\n");
    else if(flag==-2)
        printf("文件中的行数不足%d行\n",row);
    else
        printf("获取到的文本是: \n%s包含最后的换行符,长度=%d\n",s,flag);
}

读取指定行

feof()是检测流上的文件结束符的函数,如果文件结束,则返回非0值,否则返回0

#include <stdio.h>
#include "readline.h"
// 读取文件指定一行
int ReadLine1(const char *fileName, char outBuf[], int n){

	int  whichLine = n;                //指定要读取哪一行
	int  currentIndex = 1;             //当前读取的行

	char buf[1024] = { 0 };            //临时 不能做返回值 防止局部数组被释放后非法访问内存

	FILE *file;
	int isOpen = fopen_s(&file, fileName, "r");
	if (isOpen != 0) {
		printf("文件打开失败\n");
		return -1;
	}

	while (!feof(file)){

		if (currentIndex == whichLine){
			fgets(outBuf, 1024, file);     //读取一行  必须用数组
			break;
		}
		fgets(buf, 1024, file);            //临时数组读取一行,并定位到下一行
		currentIndex++;

	}
	fclose(file);

	return 0;
}


5.提取包含特定内容的所有行

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int find(char *str,char ch)
{
    int i;
    for(i=0;i<strlen(str);i++)
    {
        if(str[i]==ch)
        {
            return 1;
        }
    }
    return 0;
}
void change(char *str,char ch1,char ch2)
{
    int i;
    for(i=0;i<strlen(str);i++)
    {
        if(str[i]==ch1)
        {
            str[i]=ch2;
        }
    }
}
void deletestr(char*str,char ch)
{
    int i;
    for(i=0;i<strlen(str);i++)
    {
        if(str[i]==ch)
        {
            str[i]='\0';
        }
    }
}
int main()
{
    ifstream input("1.dat");
    ofstream output("2.dat");
    char str[50];
    do{
        input>>str;
        if(find(str,'A'))
        {
            change(str,'A','B');
            deletestr(str,'C');
            if(str!=NULL)
            {
                output<<str<<endl;
            }
        }
    }while(!input.eof());
    input.close();
    output.close();
    return 0;
}

在这里插入图片描述
在这里插入图片描述

读取包含指定内容的行数

#include  <stdio.h>   
#include  <stdlib.h>   
#include  <string.h>   
#include  <unistd.h>
int  main()  
{         
	char  *filename  =  "./example.txt";  //  替换为您的文件名         
	char  *search_string  =  "target_string";  //  替换为您要搜索的字符串         
	int  count  =  0;      
	FILE  *file  =  fopen(filename,  "r");         
	if  (file  ==  NULL)  
	{             
		perror("Error  opening  file");             
		return  1;        
	} 
	     
	char  line[256];         
	while(fgets(line,  sizeof(line),  file)!=  NULL)  
	{            
	   if  (strstr(line,  search_string)!=  NULL)
		   { 
	         count++;             
		   }         
	}    
	  
	fclose(file);         
	printf("Number  of  lines  containing  the  target  string  %d \n",  count);      
	return  0;   
} 

6.获取所在行

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>
#include  <unistd.h>
/*
char  *filename     :path
char  *search_string: string
*/
int  get_linenum(char  *filename, char  *search_string)
{
	//char  *filename  =  "./example.txt";  //  替换为您的文件名         
	//char  *search_string  =  "target_string";  //  替换为您要搜索的字符串      
    char  line[1024];
	int num=0;	
	int  count  =  0;
	FILE  *file  =  fopen(filename,  "r");
	if  (file  ==  NULL)
	{
		perror("Error  opening  file");
		return  1;
	}
	
	while  (fgets(line,  sizeof(line),  file)!=  NULL)
	{
		num++;
	    if  (strstr(line,  search_string)!=  NULL)
	    {
			count++;
			break;
	    }
	}
	fclose(file);
	//printf("Number  of  lines  containing  the  target  string  %d line num: %d \n",  count,num);
	return  num;
}


int main()
{
	printf("%d\n", get_linenum("./example.txt", "target_string"));
}

7.清空字符串

char a[ ]="aaaaaaaa";               //定义字符数组
for (unsigned int i = 0; i < strlen(a); i++)
      a[i] = '\0' ;                      //for循环清空数组 

memset包含在头文件string.h中,函数原型为:memset(void *s,int ch,size_t n)。

char a[ ]="aaaaaaaa";            //定义字符数组
memset(a, 0, sizeof(a));          //清空数组 

直接使用strcpy将一个空串赋值给字符串就可以,需要string.h

char ss[11] = {"hello world"}; //当前为hello world
strcpy(ss, "");
//现在的ss就是空串了

8.字符串给二维数组赋值

 char newpath[5][10];
 strcpy(newpath[0], devnode); 
char str[3][10] = {"hello", "world", "c"}; 
char str[3][10]; 
FILE *fp = fopen("file.txt", "r"); 
if (fp != NULL) { 
    int i = 0; 
    while (fgets(str[i], 10, fp) != NULL && i < 3) { 
        i++; 
    } 
    fclose(fp); 
} 

逐个打印16进制数据HEX

#include <stdio.h>
#include <string.h>

void printHex(const char* str) {
    size_t len = strlen(str);

    for (size_t i = 0; i < len; i++) {
        printf("%02X ", str[i]);
    }
    printf("\n");
}

int main() {
    const char* str = "Hello, World!";
    printHex(str);

    return 0;
}
#include <stdio.h>

void DebugSendBuf(unsigned char *buf, unsigned int len) {
    int i = 0;
    for (i = 0; i < len; i++) {
        printf("%02x ", buf[i]);
        if ((i + 1) % 16 == 0 && i != 0) {
            printf("  ");
        }
        if ((i + 1) % 32 == 0 && i != 0) {
            printf("\n");
        }
    }
    printf("\n");
}

int main() {
    unsigned char buf[] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFC};

    unsigned int length = sizeof(buf) / sizeof(buf[0]);

    DebugSendBuf(buf, length);

    return 0;
}
#include <stdio.h>

void DebugSendBuf(unsigned char *buf, unsigned int len) {
    int i = 0;
    for (i = 0; i < len; i++) {
        printf("%02x ", buf[i]);
        if ((i + 1) % 16 == 0 && i != 0) {
            printf("  ");
        }
        if ((i + 1) % 32 == 0 && i != 0) {
            printf("\n");
        }
    }
    printf("\n");
}

int main() {
    unsigned char buf[] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFC};

    unsigned int length = sizeof(buf) / sizeof(buf[0]);

    DebugSendBuf(buf, length);

    return 0;
}

这段代码中的 DebugSendBuf 函数用于以十六进制形式打印一个无符号字符指针 buf 所指向的数据缓冲区,并指定打印的字节长度 len。
函数通过一个循环遍历每个字节,并使用 %02x 格式说明符打印每个字节的十六进制表示,并在每行结束时添加换行符。
根据代码的逻辑,每打印 16 个字节后会在每行中间添加额外的空格,而每打印 32 个字节后会在每行之间插入换行符。

修改指定字符串后边的内容

要在 Linux C 中修改一个文本文件中指定字符串所在行,并且为该行字符串后面的内容,可以按照以下步骤进行操作:

  1. 打开文件并逐行读取文件的内容,使用标准 C 库函数 fgets()
  2. 在每行中查找指定的字符串,使用标准 C 库函数 strstr()strchr(),如果找到,则执行下一步操作。
  3. 根据找到的字符串所在的位置,计算出该行字符串后面内容的位置。
  4. 通过文件指针定位到该行,使用标准 C 库函数 fseek()
  5. 把需要修改的新字符串写入到该行的内存缓冲区,使用标准 C 库函数 snprintf()
  6. 关闭文件,保存修改。

下面是示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    FILE *fp;
    char *filename = "/path/to/file.txt"; // 文件路径及文件名
    char *searchstr = "指定字符串"; // 需要查找的字符串
    char *newstr = "新的字符串"; // 需要写入到指定行后面的新字符串
    int searchstrlen = strlen(searchstr);
    int newstrlen = strlen(newstr);
    char buf[BUFSIZ]; // 读取文件时的缓冲区
    char *pos;
    long offset;
    int found = 0; // 标识是否找到了指定字符串

    fp = fopen(filename, "r+");
    if (fp == NULL) {
        perror("打开文件");
        exit(EXIT_FAILURE);
    }

    // 逐行查找目标字符串
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        pos = strstr(buf, searchstr);
        if (pos) {
            found = 1;

            // 计算需要修改的内容的偏移量
            offset = ftell(fp) - strlen(buf) + (pos - buf) + searchstrlen;

            // 定位到目标行
            if (fseek(fp, -(long)strlen(buf), SEEK_CUR) != 0) {
                perror("定位到指定行");
                exit(EXIT_FAILURE);
            }

            // 写入新字符串
            if (snprintf(buf, sizeof(buf), "%s%s\n", searchstr, newstr) < 0) {
                perror("写入新字符串");
                exit(EXIT_FAILURE);
            }

            if (fwrite(buf, strlen(buf), 1, fp) != 1) {
                perror("写入文件");
                exit(EXIT_FAILURE);
            }

            break; // 找到了就跳出循环
        }
    }

    if (!found) {
        printf("未找到指定字符串\n");
    }

    fclose(fp);

    return 0;
}

在这个例子中,我们打开文本文件,在逐行读取文件内容的过程中查找指定字符串。如果找到了,则计算出需要修改内容的偏移量,并使用 fseek() 函数定位到该行。然后,把新的字符串写入到该行的内存缓冲区中,并使用 fwrite() 函数写入到文件中。

追加到最后一行,打印记录

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define MAX_RECORDS 10
#define FILENAME "error_records.txt"

// 函数声明
void appendRecord(uint32_t error_code);
void printRecords();

int main() {
    uint32_t error_code;
    printf("Enter error code (32-bit): ");
    scanf("%u", &error_code);

    // 追加记录
    appendRecord(error_code);

    // 打印记录
    printf("Records:\n");
    printRecords();

    return 0;
}

// 追加记录到文件末尾
void appendRecord(uint32_t error_code) {
    FILE *file = fopen(FILENAME, "r+");
    if (file == NULL) {
        printf("Error opening file.\n");
        exit(1);
    }

    // 统计当前记录的数量
    uint32_t current_records = 0;
    char line[100]; // 假设一行最多100个字符
    while (fgets(line, sizeof(line), file) != NULL) {
        current_records++;
    }

    // 如果记录数量超过最大值,则从第一行开始逐行替换
    if (current_records >= MAX_RECORDS) {
        rewind(file); // 定位到文件开头

        // 覆盖第一行及之后的记录
        for (int i = 0; i < MAX_RECORDS - 1; i++) {
            fgets(line, sizeof(line), file); // 读取下一行
            fseek(file, 0, SEEK_CUR); // 移动文件指针到当前位置(确保偏移量为0)
        }
    } else {
        fseek(file, 0, SEEK_END); // 定位到文件末尾
    }

    // 写入错误码到文件
    fprintf(file, "%u\n", error_code);
    
    fclose(file);
}

// 打印记录
void printRecords() {
    FILE *file = fopen(FILENAME, "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        exit(1);
    }

    uint32_t error_code;
    int count = 0;

    // 读取并打印记录
    while (fscanf(file, "%u", &error_code) != EOF && count < MAX_RECORDS) {
        printf("%u\n", error_code);
        count++;
    }

    fclose(file);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值