C++ String Functions and examples
example 1
char s1[20]="dir/bin/app1", s2[20]="file.asm",s3[20];
char *p;
int result;
- Length int strlen(char *s);
cout << strlen(s1) <<endl; //Output is 12.
cout << strlen(s2) <<endl; //Output is 8
- Copy char *strcpy(char *s1, *s2);
strcpy(s3,s1); //s3 ="dir/bin/app1"
- Concatenation char *strcat(char *s1, *s2);
strcat(s3,"/");
strcat(s3,s2); //s3 ="dir/bin/app1/file.asm"
- Compare int *strcmp(char *s1, *s2);
result=strcmp("baker", "Baker"); //result>0
result=strcmp("12","12"); // result=0
result=strcmp("Joe","Joseph"); // result< 0
- Index char *strchr(char *s, int c);
p=strchr(s2,'.'); // p points at '.' after file.
if (p)
strcpy(p,".cpp"); //s2="file.cpp"
- 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"
- Read StreamVariable>> s
- Write StreamVariable << s
cin >> s1; //If Input is "hello world"
cout << s1; // s1 is "hello"
//Output is "hello"