linux_C语言_07 字符型数组,字符串常用函数

2010-08-11  分类:C 标签:  作者:fanzg


这是有声音的视频,请检查播放器或者声音输出设备。

这次学习的内容:字符型数组,字符串常用函数

//=======================================

char s[3] = {'a','b','c'};

char s[3];
s[0] = 'a';
s[1] = 'b';
s[2] = 'c';

--------------------

#include <stdio.h>

main()
{
char s1[10], s2[10];

scanf( "%s%s", s1, s2 );

printf( "s1=%s, s2=%s\n", s1, s2 );
}

并不像 int a[10], 通过一个 for 循环进行输入。也是通过空格分开

//===========================================
统计 用户输入字符串当中某个字符出现的次数

#include <stdio.h>

main()
{
char s[100];

int i=0,count=0;

scanf( "%s",s );

while( s[i] != '\0' )
{
if( s[i] == 'a' )
count++;
i++;
}

printf( "字符a出现了 %d 次\n", count );
}

-------------------

[17rumen@localhost ~]$ ./a.out
hjhiuoyanm,nljwkeayuihafdfd
字符a出现了 3 次

//=========================================

介绍一下 字符串的一些常用函数

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

main()
{
char s[20] = {"abcd\0iiii"};

printf( "%d \n", strlen( s ) );
}

[17rumen@localhost ~]$ gcc c_07.c
c_07.c: In function ‘main’:
c_07.c:8: warning: incompatible implicit declaration of built-in function ‘strlen’

注意要包含 #include <string.h> 头文件,因为使用到 strlen()函数

puts( str1 ) 和 gets( str1 ) , 函数只能输入或者输出一个字符串

gets( str1 )  在 gcc 下不能使用了 , 取代的就是 fgets

[17rumen@localhost ~]$ gcc c_07.c
/tmp/ccCcozhH.o: In function `main':
c_07.c:(.text+0x18): warning: the `gets' function is dangerous and should not be used.

fgets 和  fputs    的用法

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

main()
{
char s[20];

//      gets(s);
fgets( s, 20, stdin );

//      puts( s );
fputs( s, stdout );

}

//=====================================================

strcmp( s1, s2 ) 字符串的比较 ,

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

main()
{
char s1[5] = "abcd";
char s2[5] = "abck";

int r = strcmp( s1, s2 );

if( r > 0 )
printf( "s1 > s2 \n" );
else if( r == 0 )
printf( "s1 == s2 \n" );
else
printf( "s1 < s2 \n" );
}

--------------------------------
strcpy( temp, s1 ) 字符串拷贝

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

main()
{
char temp[5], s1[5] = "abcd";

strcpy( temp , s1 );

printf( "%s \n", temp );
}

视频就到这里了。。88


“linux_C语言_07 字符型数组,字符串常用函数”没有评论

有任何疑问或建议,可以给作者留言:



公告:

  • 2010年5月之前的视频是文字解说演示,没有声音。
  • 2010年5月以后的视频全部带声音。