You are on page 1of 12

STRINGS IN C

Strings are actually one-dimensional array of characters terminated by a null character


'\0'. The difference between a character array and a string is the string is terminated with a
special character ‘\0’.

Declaration of strings:
Declaring a string is as simple as declaring a one dimensional array. Below is the basic
syntax for declaring a string.

char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used
define the length of the string, i.e the number of characters strings will store. Please keep in
mind that there is an extra terminating character which is the Null character (‘\0’) used to
indicate termination of string which differs strings from normal character arrays.
Initializing a String:
A string can be initialized in different ways. We will explain this with the help of an
example. Below is an example to declare a string with name as str and initialize it with
“GeeksforGeeks”.
1. char str[] = "GeeksforGeeks";
2. char str[50] = "GeeksforGeeks";
3. char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

Formatting Strings
By now you have seen most of the format conversion possible, but there is one type that
is a little different and that are string format conversions. Take a look at the following
example:
#include<stdio.h>
main()
{
printf(":%s:\n", "Hello, world!");
printf(":%15s:\n", "Hello, world!");
printf(":%.10s:\n", "Hello, world!");
printf(":%-10s:\n", "Hello, world!");
printf(":%-15s:\n", "Hello, world!");
printf(":%.15s:\n", "Hello, world!");
printf(":%15.10s:\n", "Hello, world!");
printf(":%-15.10s:\n", "Hello, world!");
}
The output of the example above:

:Hello, world!:
: Hello, world!:
:Hello, wor:
:Hello, world!:
:Hello, world! :
:Hello, world!:
: Hello, wor:
:Hello, wor :

As you can see, the string format conversion reacts very different from number format
conversions.

 The printf(“:%s:\n”, “Hello, world!”); statement prints the string (nothing special
happens.)
 The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but print 15
characters. If the string is smaller the “empty” positions will be filled with
“whitespace.”
 The printf(“:%.10s:\n”, “Hello, world!”); statement prints the string, but print only
10 characters of the string.
 The printf(“:%-10s:\n”, “Hello, world!”); statement prints the string, but prints at
least 10 characters. If the string is smaller “whitespace” is added at the end. (See
next example.)
 The printf(“:%-15s:\n”, “Hello, world!”); statement prints the string, but prints at
least 15 characters. The string in this case is shorter than the defined 15 character,
thus “whitespace” is added at the end (defined by the minus sign.)
 The printf(“:%.15s:\n”, “Hello, world!”); statement prints the string, but print only
15 characters of the string. In this case the string is shorter than 15, thus the whole
string is printed.
 The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string, but print 15
characters.
If the string is smaller the “empty” positions will be filled with “whitespace.” But it
will only print a maximum of 10 characters, thus only part of new string (old string
plus the whitespace positions) is printed.
 The printf(“:%-15.10s:\n”, “Hello, world!”); statement prints the string, but it does
the exact same thing as the previous statement, accept the “whitespace” is added at
the end.
Example
#include <stdio.h>
int main()
{
char str[] = "geeksforgeeks";
printf("%20s\n", str);
printf("%-20s\n", str);
printf("%20.5s\n", str);
printf("%-20.5s\n", str);
return 0;
}
Output:
geeksforgeeks
geeksforgeeks
geeks
geeks

C String Functions
No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, copies the contents of source string to destination


source) string.

3) strcat(first_string, concats or joins first string with second string. The


second_string) result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both


second_string) strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.


C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
Length of string is: 10

C Copy String: strcpy()

The strcpy(destination, source) function copies the source string in destination.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint

C String Concatenation: strcat()

The strcat(first_string, second_string) function concatenates two strings and result is


returned to first_string.

#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Output:
Value of first string is: helloc

C Compare String: strcmp()

The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.

Here, we are using gets() function which reads string from the console.

#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()

The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj

C String Lowercase: strlwr()

The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint

C String Uppercase: strupr()

The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT

String Conversion functions

Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
Int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
double strtod( const char *nPtr, char
Converts the string nPtr to double.
**endPtr )
long strtol( const char *nPtr, char **endPtr,
Converts the string nPtr to long.
int base )
unsigned long strtoul( const char *nPtr, char
Converts the string nPtr to unsigned long.
**endPtr, int base )

Use of String Conversion functions:

While writing main () in a program, we can put them inside the parentheses of main. ‘int
arg c, char ** arg v are written inside the parentheses. The arg c is the count of number of
arguments passed to the program including the name of the program itself while arg v is a
vector of strings or an array of strings. It is used while giving command line arguments to
the program.

The arguments in the command line will always be character strings. The number in the
command line (for example 12.8 or 45) are stored as strings. While using the numbers in
the program, we need these conversion functions.

Following is a simple program which demonstrate the use of atoi function. This program
prompts the user to enter an integer between 10-100, and checks if a valid integer is
entered.
//This program demonstrate the use of atoi function
# include <iostream.h>
# include <stdlib.h>
main( )
{
int anInteger;
char myInt [20]
cout << "Enter an integer between 10-100 : ";
cin >> myInt;
if (atoi(myInt) == 0)
cout << "\nError : Not a valid input"; // could be non numeric
else
{
anInteger = atoi(myInt);
if (anInteger < 10 || anInteger > 100)
cout << "\nError : only integers between 10-100 are allowed!";
else
cout << "\n OK, you have entered " << anInteger;
}
}

The output of the program is as follows.

Enter an integer between 10-100 : 45.5

OK, you have entered 45

atol(): This function converts a C-type string, passed as an argument to function call, to a
long integer. It parses the C-string str interpreting its content as an integral number, which
is returned as a value of type long int. The function discards the whitespace characters
present at the beginning of the string until a non-whitespace character is found. If the
sequence of non-whitespace characters in C-string str is not a valid integral number, or if
no such sequence exists because either str is empty or it contains only whitespace
characters, no conversion is performed and zero is returned.
Syntax:
long int atol ( const char * str )
int main()
{
// char array of numbers
char str1[] = "5672345";
// Function calling to convert to a long int
long int num1 = atol(str1);
cout << "Number is " << num1 << "\n";
// char array of numbers of spaces
char str2[] = "10000002 0";
// Function calling to convert to a long int
long int num2 = atol(str2);
cout << "Number is " << num2 << "\n";
return 0;
}
Output:
Number is 5672345
Number is 10000002

atof() function: This function converts a C-type string, passed as an argument to function
call, to double. It parses the C-string str interpreting its content as a floating point number,
which is returned as a value of type double. The function discards the whitespace
characters present at the beginning of the string until a non-whitespace character is found.
If the sequence of non-whitespace characters in C-string str is not a valid floating point
number, or if no such sequence exists because either str is empty or it contains only
whitespace characters, no conversion is performed and 0.0 is returned.
Syntax:
double atol ( const char * str )
int main()
{
// char array
char pi[] = "3.1415926535";
// Calling function to convert to a double
double pi_val = atof(pi);
// prints the double value
cout << "Value of pi = " << pi_val << "\n";
// char array
char acc_g[] = "9.8";
// Calling function to convert to a double
double acc_g_val = atof(acc_g);
// prints the double value
cout << "Value of acceleration due to gravity = "
<< acc_g_val << "\n";
return 0;
}
Output:
Value of pi = 3.14159
Value of acceleration due to gravity = 9.8
strtol
C library function long int strtol(const char *str, char **endptr, int base) converts the
initial part of the string in str to a long int value according to the given base, which must
be between 2 and 36 inclusive, or be the special value 0.

Declaration

Following is the declaration for strtol() function.

long int strtol(const char *str, char **endptr, int base)

Parameters

 str − This is the string containing the representation of an integral number.


 endptr − This is the reference to an object of type char*, whose value is set by the
function to the next character in str after the numerical value.
 base − This is the base, which must be between 2 and 36 inclusive, or be the special
value 0.

Return Value

This function returns the converted integral number as a long int value, else zero value is
returned.

Example

The following example shows the usage of strtol() function.

#include <stdio.h>
#include <stdlib.h>

int main () {
char str[30] = "2030300 This is test";
char *ptr;
long ret;

ret = strtol(str, &ptr, 10);


printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);

return(0);
}
Let us compile and run the above program that will produce the following result −
The number(unsigned long integer) is 2030300
String part is | This is test|

C library function - strtod()

Description

The C library function double strtod(const char *str, char **endptr) converts the string
pointed to by the argument str to a floating-point number (type double). If endptr is not
NULL, a pointer to the character after the last character used in the conversion is stored in
the location referenced by endptr.

Declaration

Following is the declaration for strtod() function.

double strtod(const char *str, char **endptr)

Parameters

 str − This is the value to be converted to a string.


 endptr − This is the reference to an already allocated object of type char*, whose
value is set by the function to the next character in str after the numerical value.

Return Value

This function returns the converted floating point number as a double value, else zero
value (0.0) is returned.

Example

The following example shows the usage of strtod() function.

#include <stdio.h>
#include <stdlib.h>

int main () {
char str[30] = "20.30300 This is test";
char *ptr;
double ret;

ret = strtod(str, &ptr);


printf("The number(double) is %lf\n", ret);
printf("String part is |%s|", ptr);
return(0);
}
Let us compile and run the above program that will produce the following result −
The number(double) is 20.303000
String part is | This is test|

You might also like