Strings are a very useful data type. The entire internet thrives on the exchange of information as text data in the form of HTML, CSS and JavaScript files. The browser parses this text in order to know what to display on your computer or phone screen or which files to ask the server for. The very code we write is in text. Our code editor needs to be able to manipulate this text in order to display it in the proper syntax highlighting.
This means that having methods to process strings is very important. C has some methods that we can use in order to manipulate strings.
- strlen can be used to find the length of a string:
#include <stdio.h>
#include <string.h>
int main(void){
char name[] = "Joash Gobin";
int length = strlen(name);
printf("The length of the string %s is %d\n",name,length);
for (int i=0;i<length;i++){
printf("name[%d] = %c\n",i,name[i]);
}
return 0;
}
spelling-your-name.c Copy
- strcpy is used to copy the second string into the first string
- strcat is used to concatenate the second string onto the end of the first string
Here are some of these functions in use:
#include <stdio.h>
#include <string.h>
int main(){
char first_name[] = "John";
char last_name[] = "Doe";
char buffer[100];
printf("Before concatenation:\n");
printf("The first name is %s\n",first_name);
printf("The last name is %s\n",last_name);
printf("0 - The buffer is currently: %s\n",buffer);
// strcat(destination, source);
strcat(buffer,first_name);
printf("1 - The buffer is currently: '%s'\n",buffer);
strcat(buffer," ");
printf("2 - The buffer is currently: '%s'\n",buffer);
strcat(buffer,last_name);
printf("3 - The buffer is currently: '%s'\n",buffer);
char buffer_2[100] = "Hello there";
printf("4 - Buffer 2 is currently: '%s'\n",buffer_2);
strcpy(buffer_2,buffer);
printf("5 - Buffer 2 is currently: '%s'\n",buffer_2);
return 0;
}
string-functions-overview.c Copy