String in C

Introduction to string

A string is generally called a sequence of characters. In C programming array of characters is called a string.

"Alex", "C-Programming", "Work with C", "008899770011"  are some examples of strings.

In C programming each string ends with a special character called NULL(\0) character. Ascii of NULL(\0) character is 0.

Note: Remember '\0' ASCII is 0 whereas ASCII of '0' is 48. so NULL('\0') and zero('0') character is different.

Note: As well if you are storing 4 characters string into character array then it occupies space of 5 characters because every string ends with NULL(\0) character in C-programming.

Declaring string in C

To declare a string type variable, we can use a character array. so string declaration is similar as the array declaration as shown in the code snippet below...

char s[20]; //20 is the maximum size of string

Initialization of string

As similar to any other type of array, string array can be initialized with a sequence of characters terminated by a NULL(\0) character.

Even String is generally used so another way to write string constant is to enclose string constants in double-quotes.

The following code snippet demonstrates how to initialize strings in C.

char s[20] = {'I','D','I','O','T','S',' ','D','I','A','R','Y','\0'};

As shown in the above example, character array is initialized with a sequence of characters, each character is separated by a comma. Observe carefully that string ends with NULL(\0) characters.

char s[20] = "IDIOTS DIARY";

As shown in the above code snippet, a string is directly initialized with string constant which is enclosed in double-quotes. In this case, you don't need to specify NULL character at the end of a string constant. it is automatically added at the end of the string array.

char s[] = "IDIOTS DIARY";

If you are initializing a string, the size of the array is automatically adopted by the size of the initialized string constant.

User input in a string

A string is a mostly used data type in programming and receiving input in a string is a very common task. There are many ways to receiving input in a string as shown below...

In C, %s format specifier is used to working with string and we can use %s format specifier to receive input and printing string output in C.

Note: There is no format specifier to print the whole array of other types except string.

The following example demonstrates, how to input/output string using %s format specifier.

Receiving input in a string

#include<stdio.h>
int main() {
	char s[20];
	printf("Enter any string: ");
	scanf("%s",s);
	
	printf("Output = %s\n",s);
	return 0;
}
Sample Output
Enter any string: IdiotsDiary
Output = IdiotsDiary

Enter any string: Idiots Diary
Output = Idiots
As shown in the above example, %s format specifier doesn't receive input after space. It is terminated by space character.

The remaining part of the string which doesn't store in the string variable remains in the keyboard buffer(stdin) and received in next subsequent input of string.

Note: While reading string &(address-of) sign with the string variable in scanf(), because array name represents the base address of an array. so no need to specify the &(address-of) operator with a string variable.

Reading spaces in a string

Another method to read a string with spaces by using gets() function, It is a function used to read string input and don't terminate by the space character.

#include<stdio.h>
int main() {
	char s[20];
	printf("Enter any string: ");
	gets(s);	
	printf("Output = %s\n",s);
	return 0;
}
Sample Output
Enter any string: Idiots Diary
Output = Idiots Diary

Enter any string: Learn all about c programming with Idiotsdiary
Output = Learn all about c programming with Idiotsdiary

As shown in the above example, gets() is able to read spaces in a string input, but the problem with that it doesn't check the input limit and read the whole string and try to store in the above code snippet.

When you try to store a string, which is larger than the array size the character fall outside the array and store in the invalid memory location that is not allocated to your program. Which causes a run-time error or terminate your program.

To prevent the above problem, another method is fgets() should use. It reads data from a stream(source) with the limit specified after the limit inputs are ignored.

The following example shows you the use of fgets() function.

Reading string using fgets()

#include<stdio.h>
int main() {
	char s[20];
	printf("Enter any string: ");
	fgets(s,20,stdin);
	printf("Output = %s\n",s);
	return 0;
}
Sample Output
Enter any string: Learn all about c programming with Idiotsdiary
Output = Learn all about c p
In the above example stdin is the source from where you want to read data. In c, stdin refers to standard input device which is keyboard by default.

Filtering string input

There are other ways available in c to receive filter string input. For example, sometimes you want to input only lower case alphabets in string input and ignore uppercase. There is a way to terminate the string input as soon as the uppercase character found in the string as shown in the following example.

Filtering lowercase inputs

#include<stdio.h>
int main() {
	char s[20];
	printf("Enter any string: ");
	scanf("%[a-z]s",s);
	printf("Output = %s\n",s);
	return 0;
}
Sample output
Enter any string: welcome Idiotsdiary
Output = welcome
[a-z] in scanf() specify that only lowercase alphabet range is allowed in string input.

Reading Spaces

scanf("%[^\n]s",s); will receive input until a new line character is not found so it is able to read input. ^(caret) sign represents not.
#include<stdio.h>
int main() {
	char s[20];
	printf("Enter any string: ");
	scanf("%[^\n]s",s);
	printf("Output = %s\n",s);
	return 0;
}
Sample Output:
Enter any string: Hello IdiotsDiary
Output = Hello IdiotsDiary
  • To receive only alphabets(lowercase and uppercase) use the expression [A-Za-z]
  • To receive everything but don't allow digits use the expression [^0-9].
  • For more other pattern learn regex expression.

Program to find the length of a string

#include<stdio.h>
int main() {
	char s[20];
	int i,l;
	
	printf("Enter any string: ");
	fgets(s,20,stdin);
	
	i = 0;l = 0;
	while(s[i] != '\0') {
		i++;
		l++;
	}
	
	printf("String length = %d",l);
	
	return 0;
}

Explanation:

To calculate the length of the string, count the character until NULL(\0) character is encountered.

Output:

Enter any string: Idiots Diary
String length = 13

If you observe carefully while variable i reaches to the NULL character loop terminates and In this case variable, i represent the length of the string. so no need to use the extra variable for counting string length as shown in the example below...

i = 0;
while(s[i] != '\0') {
  i++;
}

printf("String length = %d",i);

As we have already learned that the ASCII value of NULL(\0) character is 0 and zero is treated as false and any non-zero value is treated as true. so the above code can be updated as given below...

i = 0;
while(s[0]) {
    i++;
}
printf("String length = %d",i);
Note: In c programming, there is a library function strlen() to calculate the string length. All the string related functions are defined in a string library string.h.

Program to copy a string into another string using function xstrcpy()

#include<stdio.h>
void xstrcpy(char dest[],char src[]) {
	int i = 0;
	while(src[i]) {
		dest[i] = src[i];
		i++;
	}
}
int main() {
	char src[20],dest[20];
	
	printf("Enter the source string: ");
	fgets(src,20,stdin);
	
	xstrcpy(dest,src);
	
	printf("Destination = %s",dest);
	
	return 0;
}

Output:

Enter the source string: Idiots Diary
Destination = Idiots Diary

Note: To copy a string into another string in c programming, there is a library function strcpy() defined in string.h that is used similar as the xstrcpy() function in above example.

Alternate way to xstrcpy() function

void xstrcpy(char dest[],char src[]) {
	int i = 0;
	while(dest[i] = src[i]){
              i++;
        }
}
void xstrcpy(char dest[],char src[]) {
	int i = 0;
	while(dest[i] = src[i++]);
}

Program to concatenate a string into another

#include<stdio.h>
void xstrcat(char s1[],char s2[]) {
	int i,j;
	
	j = i = 0;
	//move i after last character of s1;
	while (s1[i]) {
		i++;
	} 
	
	//copy each char of s1 into s2
	while(s2[j]) {
		s1[i] = s2[j];
		i++;
		j++;
	}
	
	//put the NULL(\0) to terminate the string properly
	s1[i] = '\0';
}
int main() {
	char s1[40],s2[20];
	
	printf("Enter first string: ");
	scanf("%s",s1);
	
	printf("Enter second string: ");
	scanf("%s",s2);
	
	xstrcat(s1,s2); //concat s2 into s1
	
	
	printf("After concat...\n----------------------\n");
	printf("String1 = %s\n",s1);
	printf("String2 = %s",s2);
	
	return 0;
}

Output

Enter first string: Hello
Enter second string: World
After concat...
----------------------
String1 = HelloWorld
String2 = World
Note: To concat a string into another library function is strcat() is used which is defined in string.h.

Program to reverse a string

#include<stdio.h>
#include<string.h>
void xstrrev(char s[]) {
	int i , j ;
	char t;
	i = 0; 
	j = strlen(s) - 1; //point the variable to the last character
	while(i < j) {
		t = s[i];
		s[i] = s[j];
		s[j] = t;
		i++;
		j--;
	}
}
int main() {
	char s[20];
	
	printf("Enter a string: ");
	gets(s);
	
	xstrrev(s);
	
	printf("Reverse string = %s",s);
	return 0;
}

Output

Enter a string: Hello friends
Reverse string = sdneirf olleH

Explanation

To reverse a string interchange the characters first and last, second and second last, and so on. To do the same take two cursors. place the first cursor to the first character of string and second cursor to the last character of string then start interchanging characters and move the cursor forward and backward.