Download presentation
Presentation is loading. Please wait.
1
CSE1320 Strings Dr. Sajib Datta
2
String functions strcat() strcpy() strtok()
3
strcat() strcat() for string concatenation
Take two strings for arguments A copy of the second string is tacked onto the end of the first, and this combined version becomes the new first string. The second string is not altered. The return type of strcat () is char *, the value of its first argument – the address of the first character of the string to which the second string is appended.
4
strcat() cont. #include <stdio.h> #include <string.h>
int main(void) { char flower[80]; char addon[] = " is a cat."; scanf("%s", flower); strcat(flower, addon); printf("%s\n",flower); return 0; } Note!!! strcat( ) not checking whether the first array is large enough to hold the second string.
5
If your input is Kitty, your output is going to be as follow.
Kitty is a cat.
6
strcpy() #include <stdio.h> #include <string.h>
int main(void) { char orig[] = "beast"; char copy[80] = "Be the best that you can be."; strcpy(copy, orig); printf("copy - %s\n", copy); printf(“orig - %s\n", orig); return 0; }
7
strcpy() #include <stdio.h> #include <string.h>
int main(void) { char orig[] = "beast"; char copy[80] = "Be the best that you can be."; strcpy(copy+7, orig); printf("copy - %s\n", copy); printf(“orig - %s\n", orig); return 0; }
8
Output copy - Be the beast orig - beast
9
strtok() #include<stdio.h> #include<string.h> void main(){ char sentence[]="Bill is really cool."; char *word = strtok(sentence," ."); printf("%s\n",word); char *secondword = strtok(NULL," ."); printf("%s\n",secondword); }
10
strtok() cont. #include<stdio.h> #include<string.h> void main(){ char sentence[]="Bill is really cool."; char *word = strtok(sentence,"xz"); printf("%s\n",word); char *secondword = strtok(NULL,"xz"); if(secondword==NULL) printf(":)\n"); }
11
strtok() cont. #include<stdio.h> #include<string.h> void main(){ char sentence[]="Bill is really cool."; char *word = strtok(sentence," ."); while(word!=NULL) { printf("%s\n",word); word = strtok(NULL," ."); }
12
strtok() cont. Is there anything wrong in this code?
#include<stdio.h> #include<string.h> void main(){ char *sentence="Bill is really cool."; char *word = strtok(sentence," ."); while(word!=NULL) { printf("%s\n",word); word = strtok(NULL," ."); }
13
Use fgets() Not gets() #include <stdio.h> int main() { char name[10]; printf("What’s your name? \n"); fgets(name,10,stdin); printf(“Nice to meet you, %s.\n",name); return(0); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.