//linux字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//常见的字符串操作
int main(){
//1 C语言中字符串的表达方式
//"abc" -> 字面值形式,可以做值,但不能做变量
//char*和char arr[]
//2 字符串的赋值: = 和strcpy()函数
// = 改地址,strcpy()改值
char* s1 = "abc";//s1指向 只读区
char s2[] = "abc";//s2是栈中,复制"abc"的值
s1 = "123";//地址可以改
//strcpy(s1,"123");//段错误,改值引发段错误
//s2 = "123";//数组是常指针,地址不可变
strcpy(s2,"123");
char* s3 = malloc(4);
//s3 = "123";//改变了指向,由堆转只读,堆内存泄漏
strcpy(s3,"123");//正确的用法
free(s3);
char buf[100] = {};//buf也用strcpy()
strcpy(buf,"123");
//3 字符串的比较(大小 和 相等)
//strcmp()全部比较 strncmp()比较前n个
//4 指针操作字符串(指针),字符串以'\0'结尾
//比如,取字符串的一部分或拆分字符串
char* s4 = "abc1234d578e9";//拆出字母和数字
char buf1[strlen(s4)+1];//字符
char buf2[strlen(s4)+1];//数字
memset(buf1,0,sizeof(buf1));
memset(buf2,0,sizeof(buf2));
int i,j,k; i=j=k=0;//右向左运算
for(;i<strlen(s4);i++){//循环字符串,到'\0'结束
if(*(s4+i)>='0' && *(s4+i)<='9'){//isdigit()
buf2[j] = *(s4+i);
j++;
}else{
buf1[k] = *(s4+i);
k++; } }
printf("%s,%s\n",buf1,buf2);
//5 字符串的拼接操作
char* dir = "/home/tarena/uc";
char* file = "a.txt";//(拼接目录名和文件名)
char buf3[50] = {};
//strcpy(buf3,dir);
//strcat(buf3,"/"); strcat(buf3,file);
sprintf(buf3,"%s/%s",dir,file);//sprintf()有用
printf("%s\n",buf3);
//6 字符串的转换(转int/double) sscanf() sprintf()
char* s5 = "1234";
int x = 0;
sscanf(s5,"%d",&x);
printf("x=%d\n",x);
char buf4[20] = {};
sprintf(buf4,"%d",x); printf("buf4=%s\n",buf4);
}
================================================================
//linux内存
#include <stdio.h>
#include <stdlib.h>
int i1 = 1; //全局
int i2;//BSS
static int i3 = 3;//全局
const int i4 = 4;//只读常量区
void fa(int i5){//栈
int i6 = 6;//栈
static int i7 = 7;//全局
const int i8 = 8;//栈
int* pi = malloc(4);//堆
char* s1 = "abc";//只读
char s2[] = "abc";//栈
printf("&i5=%p\n",&i5); printf("&i6=%p\n",&i6);
printf("&i7=%p\n",&i7); printf("&i8=%p\n",&i8);
printf("pi=%p\n",pi);
printf("s1=%p\n",s1); printf("s2=%p\n",s2);
}
int main(){
printf("&i1=%p\n",&i1); printf("&i2=%p\n",&i2);
printf("&i3=%p\n",&i3); printf("&i4=%p\n",&i4);
fa(5);
printf("fa=%p\n",fa);//函数名其实就是一个函数指针
printf("pid=%d\n",getpid());
while(1);
}
//linux获取环境变量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
extern char** environ;//全局变量,不要直接使用
char** p = environ;//使用p而不是environ
//练习:p是字符指针数组的首地址,以NULL结束
//请打印所有的环境变量字符串,NULL结束
while(*p){//p 是字符串数组,*p就是字符串
//printf("%p\n",p);
printf("%s\n",*p);
p++;// -> p = p+1;
//*p++;
//(*p)++;//错误
//*(p++);
}
char value[100]={};//数组是一个常指针,地址不可变
p = environ;//又回到了环境变量的首地址
while(*p){//练习:找到LANG的值并且存入value中
//string.h 中的strncmp()
if(!strncmp(*p,"LANG=",5)){
//value = *p;//改变地址
strcpy(value,*p+5);//*p + 5 移动了5字节
break;
}
p++;
}
printf("value=%s\n",value);
}
#include <stdio.h>
#include <stdlib.h>
int main(){
char* st = getenv("LANG");
printf("st=%s\n",st);
putenv("VAR=abc");//新增
printf("%s\n",getenv("VAR"));//abc
putenv("VAR=123");//修改
printf("%s\n",getenv("VAR"));//123
setenv("VAR","456",0);//不操作
printf("%s\n",getenv("VAR"));//123
setenv("VAR","789",1);//修改
printf("%s\n",getenv("VAR"));//789
}