C语言进阶课程学习记录 - 字符串与字符串问题分析
- 字符串
- 实验-字符串定义
- 实验-字符串作为字符数组使用
- 实验-字符串长度判断
- 小结
- 字符串问题分析
- 实验-snprintf
- 实验-字符数组,strlen,sizeof
- 实验-字符串相等比较
- 实验-循环右移
本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
字符串
实验-字符串定义
#include <stdio.h>
int main()
{
char ca[] = {'H', 'e', 'l', 'l', 'o'};
char sa[] = {'W', 'o', 'r', 'l', 'd', '\0'};
char ss[] = "Hello world!";
char* str = "Hello world!";
printf("%s\n", ca);
printf("%s\n", sa);
printf("%s\n", ss);
printf("%s\n", str);
return 0;
}
/*
output:
Hello$0@ //缺失\0
World
Hello world!
Hello world!
*/
实验-字符串作为字符数组使用
#include <stdio.h>
int main()
{
char b = "abc"[0];
char c = *("123" + 1);
char t = *"";
printf("%c\n", b);
printf("%c\n", c);
printf("%d\n", t);
printf("%s\n", "Hello");
printf("%p\n", "World");
return 0;
}
/*
output:
a
2
0
Hello
00403032
*/
实验-字符串长度判断
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Hello\0world";
int i = 0;
for(i=0; i<sizeof(s)/sizeof(char); i++)
{
printf("%c\n", s[i]);
}
printf("%s\n", s);
printf( "%d\n", strlen(s) );
printf( "%d\n", strlen("123") );
return 0;
}
/*
output:
H
e
l
l
o
w
o
r
l
d
Hello
5
3
*/
小结
C语言通过字符数组模拟字符串
C语言中的字符串使用’\0’作为结束符
字符串字面量的本质为字符数组
字符串相关函数都依赖于结束符’\0’
字符串问题分析
实验-snprintf
char buff[10]={'0'};
char src[] = "hello %s";
snprintf(buff,sizeof(buff),src);//output:hello ?a 缺失格式化信息
snprintf(buff,sizeof(buff),src,"wo");//hello wo
printf("%s\n",buff);
实验-字符数组,strlen,sizeof
#define STR "Hello, \0D.T.Software\0"
char* src = STR;
char buf[255] = {0};
snprintf(buf, sizeof(buf), src);
printf("strlen(STR) = %d\n", strlen(STR));//7
printf("sizeof(STR) = %d\n", sizeof(STR));//21+1=22
printf("strlen(src) = %d\n", strlen(src));//7
printf("sizeof(src) = %d\n", sizeof(src));//8 xx 指针的大小 4
printf("strlen(buf) = %d\n", strlen(buf));//255
printf("sizeof(buf) = %d\n", sizeof(buf));//255
printf("src = %s\n", src);//"Hello, "
printf("buf = %s\n", buf);//"Hello, "
//strlen(STR) = 7
//sizeof(STR) = 22
//strlen(src) = 7
//sizeof(src) = 4
//strlen(buf) = 7
//sizeof(buf) = 255
//src = Hello,
//buf = Hello,
实验-字符串相等比较
#define S1 "D.T.Software"
#define S2 "D.T.Software"
if( S1 == S2 )
{
printf("Equal\n");
}
else
{
printf("Non Equal\n");
}
if( strcmp(S1, S2) == 0 )
{
printf("Equal\n");
}
else
{
printf("Non Equal\n");
}
//output:
//Equal
//Equal
实验-循环右移
#include <stdio.h>
#include <string.h>
//目标字符串的指针, 结果字符串指针,移动位数
void right_shift_r(const char* src, char* result, unsigned int n)
{
const unsigned int LEN = strlen(src);
int i = 0;
for(i=0; i < LEN; i++)
{
result[(n + i) % LEN] = src[i];
}
result[LEN] = '\0';
}
int main()
{
char result[255] = {0};
right_shift_r("abcde", result, 2);
printf("%s\n", result);
right_shift_r("abcde", result, 5);
printf("%s\n", result);
right_shift_r("abcde", result, 8);
printf("%s\n", result);
return 0;
}
/*
output:
deabc
abcde
cdeab
*/