Skip to content

Working with string

Rafiul Islam edited this page Oct 29, 2018 · 4 revisions

C language support string operation functionality defined in #indclude<string.h>

Define a string

There are two way to define a string in c. One is as a pointer another is character array

char a[] = "Hello World";
char *p = "Hello World";
String length

String header supports an API called strlen(char *s) which return the length of the passed string.

char a[]  = "Hello World";
char *p = "Hello World";
int l1 = strlen(a);
int l2 = strlen(p);

For array length there is another way to find out the length of the array. Formula is total memory/one element memory. sizeof function help to find out the memory size

char arr[] = "Hello World";
int len = sizeof(arr)/sizeof(arr[0]);

String operations

It is better to use character array to define a string in c. Pointer is good but for general string operation array is more easy to understand and operate.

String copy

using character array to copy from another character array string

char s1[] = "Hello World"; // define a string
char s2[sizeof(s1)/sizeof(s1[0])]; // create a new character array to hold the copy
strcpy(s2, s1); // copy s1 data into s2

using a pointer to copy from another character array string

char s1[] = "Hello World"; // define a string
char *s2 = strdup(s1); // duplicate s1 and store the copy into s2

Copy a string from pointer to pointer

char *a = "Hello There"; // define a string
char *b; // create a new pointer
b = a; // assign the pointer address

Clone this wiki locally