C++ String Functions and examples

example 1

char s1[20]="dir/bin/app1", s2[20]="file.asm",s3[20];
char *p;
int result;
  1. Length int strlen(char *s); cout << strlen(s1) <<endl; //Output is 12. cout << strlen(s2) <<endl; //Output is 8
  2. Copy char *strcpy(char *s1, *s2); strcpy(s3,s1); //s3 ="dir/bin/app1"
  3. Concatenation char *strcat(char *s1, *s2); strcat(s3,"/"); strcat(s3,s2); //s3 ="dir/bin/app1/file.asm"
  4. Compare int *strcmp(char *s1, *s2); result=strcmp("baker", "Baker"); //result>0 result=strcmp("12","12"); // result=0 result=strcmp("Joe","Joseph"); // result< 0
  5. Index char *strchr(char *s, int c); p=strchr(s2,'.'); // p points at '.' after file. if (p) strcpy(p,".cpp"); //s2="file.cpp"
  6. RightIndex char *strrchr(char *s, int c); p=strrchr(s2,'/'); // p points at '/' after bin if (p) // Terminate string after bin. *p=0; // s2="dir/bin"
  7. Read StreamVariable>> s
  8. Write StreamVariable << s cin >> s1; //If Input is "hello world" cout << s1; // s1 is "hello" //Output is "hello"