字符串的学习记录
strlen
#include <cstdio>
#include <cstring>
int main ( int argc, char const * argv[ ] )
{
char str[ ] = "I love c" ;
printf ( "sizeof str = %d\n" , sizeof ( str) ) ;
printf ( "strlen str = %d\n" , strlen ( str) ) ;
return 0 ;
}
strcpy
#include <cstdio>
#include <cstring>
int main ( int argc, char const * argv[ ] )
{
char str1[ ] = "Original String" ;
char str2[ ] = "New String" ;
char str3[ 100 ] ;
strcpy ( str1, str2) ;
strcpy ( str3, "Copy Successful" ) ;
printf ( "str1: %s\n" , str1) ;
printf ( "str2: %s\n" , str2) ;
printf ( "str3: %s\n" , str3) ;
return 0 ;
}
strncpy
#include <cstdio>
#include <cstring>
int main ( int argc, char const * argv[ ] )
{
char str1[ ] = "To be or not to be" ;
char str2[ 40 ] ;
strncpy ( str2, str1, 5 ) ;
str2[ 5 ] = '\0' ;
printf ( "str2: %s\n" , str2) ;
return 0 ;
}
strcat strncat
#include <cstdio>
#include <cstring>
int main ( int argc, char const * argv[ ] )
{
char str1[ ] = "I love" ;
char str2[ ] = "c.com" ;
strcat ( str1, " " ) ;
strncat ( str1, str2, 5 ) ;
printf ( "str1: %s\n" , str1) ;
}
strcmp strncmp
#include <cstdio>
#include <cstring>
int main ( int argc, char const * argv[ ] )
{
char str1[ ] = "I love c" ;
char str2[ ] = "I love c1" ;
if ( ! strncmp ( str1, str2, 5 ) )
{
printf ( "两个字符串完全一致!\n" ) ;
}
else
{
printf ( "两个字符串存在差异!\n" ) ;
}
return 0 ;
}