2013年8月22日 星期四

[c/c++] strcat,strcmp,strcpy

strcat
char * strcat ( char * destination, const char * source );

輸入兩個字串,將第二個字串連接在第一個字串之後,輸出第一個字串。



Code Simple:
/* strcat example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[80];
  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}

Output:
these strings are concatenated. 

strcmp
int strcmp ( const char * str1, const char * str2 );
輸入兩個字串,比較兩個字串是否相等,相等就傳回0,第一個字串大於第二個字串傳回正數,相反則傳回負數。

Code Simple:
#include <stdio.h>
#include <string.h>

int main ()
{
char szKey[] = "apple\n";
char szInput[80];
do {
printf ("Guess my favorite fruit? ");
fgets (szInput,80,stdin);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
Output:
Guess my favourite fruit? orange
Guess my favourite fruit? apple
Correct answer!
 
strcpy
char * strcpy ( char * destination, const char * source );
將第二個參數的字串複製進第一個參數,並傳回第一個參數
 
Code Simple:
/* strcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}
Output:
str1: Sample string
str2: Sample string
str3: copy successful

沒有留言:

張貼留言

Google Analytics初學者入門簡介