Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

C Strings

strings

Uploaded by

vani shree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Strings

strings

Uploaded by

vani shree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

C Strings

The string can be defined as the one-


dimensional array of characters terminated
by a null ('\0'). The character array or the
string is used to manipulate text such as
word or sentences. Each character in the
array occupies one byte of memory, and the
last character must always be 0. The
termination character ('\0') is important in a
string since it is the only way to identify
where the string ends. When we define a
string as char s[10], the character s[10] is
implicitly initialized with the null in the
memory.
There are two ways to declare a string in c
language.
By char array
By string literal
Let's see the example of declaring string
by char array in C language.
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n',
't', '\0'};
As we know, array index starts from 0, so it
will be represented as in the figure given
below.
65.9M
1.1K
Hello Java Program for Beginners
Next
Stay

While declaring string, size is not


mandatory. So we can write the above code
as given below:

char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't'
, '\0'};
We can also define the string by the
string literal in C language. For example:
char ch[]="javatpoint";
In such case, '\0' will be appended at the
end of the string by the compiler.
Difference between char array and string literal
There are two main differences between
char array and literal.
We need to add the null character '\0' at the
end of the array by ourself whereas, it is
appended internally by the compiler in the
case of the character array.
The string literal cannot be reassigned to
another set of characters whereas, we can
reassign the characters of the array.
String Example in C
Let's see a simple example where a string is
declared and being printed. The '%s' is used
as a format specifier for the string in c
language.

#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', '
n', 't', '\0'};
char ch2[11]="javatpoint";

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);

return 0;
}
Output
Char Array Value is: javatpoint
String Literal Value is: javatpoint
Traversing String
Traversing the string is one of the most
important aspects in any of the
programming languages. We may need to
manipulate a very large text which can be
done by traversing the text. Traversing
string is somewhat different from the
traversing an integer array. We need to
know the length of the array to traverse an
integer array, whereas we may use the null
character in the case of string to identify the
end the string and terminate the loop.
Hence, there are two ways to traverse a
string.
By using the length of string
By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the
number of vowels in a string.

#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s
[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output
The number of vowels 4
Using the null character
Let's see the same example of counting the
number of vowels by using the null
character.

#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s
[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output
The number of vowels 4
Accepting string as the input
Till now, we have used scanf to accept the
input from the user. However, it can also be
used in the case of strings but with a
different scenario. Consider the below code
which stores the string while space is
encountered.

#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}
Output
Enter the string?javatpoint is the
best
You entered javatpoint
It is clear from the output that, the above
code will not work for space separated
strings. To make this code working for the
space separated strings, the minor changed
required in the scanf function, i.e., instead
of writing scanf("%s",s), we must write:
scanf("%[^\n]s",s) which instructs the
compiler to store the string s while the new
line (\n) is encountered. Let's consider the
following example to store the space-
separated strings.

#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%[^\n]s",s);
printf("You entered %s",s);
}
Output
Enter the string?javatpoint is the
best
You entered javatpoint is the best
Here we must also notice that we do not
need to use address of (&) operator in scanf
to store a string since string s is an array of
characters and the name of the array, i.e., s
indicates the base address of the string
(character array) therefore we need not use
& with it.
Some important points
However, there are the following points
which must be noticed while entering the
strings by using scanf.
The compiler doesn't perform bounds
checking on the character array. Hence,
there can be a case where the length of the
string can exceed the dimension of the
character array which may always overwrite
some important data.
Instead of using scanf, we may use gets()
which is an inbuilt function defined in a
header file string.h. The gets() is capable of
receiving only one string at a time.
Pointers with strings
We have used pointers with the array,
functions, and primitive data types so far.
However, pointers can be used to point to
the strings. There are various advantages of
using pointers to point strings. Let us
consider the following example to access
the string via the pointer.

#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
char *p = s; // pointer p is pointing to stri
ng s.
printf("%s",p); // the string javatpoint is pr
inted if we print p.
}
Output
javatpoint
As we know that string is an array of
characters, the pointers can be used in the
same way they were used with arrays. In
the above example, p is declared as a
pointer to the array of characters s. P
affects similar to s since s is the base
address of the string and treated as a
pointer internally. However, we can not
change the content of s or copy the content
of s into another string directly. For this
purpose, we need to use the pointers to
store the strings. In the following example,
we have shown the use of pointers to copy
the content of a string into another.
#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\
n");
q = p;
printf("String q: %s\n",q);
}
Output
String p: hello javatpoint
copying the content of p into q...
String q: hello javatpoint
Once a string is defined, it cannot be
reassigned to another set of characters.
However, using pointers, we can assign the
set of characters to the string. Consider the
following example.

#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("Before assigning: %s\n",p);
p = "hello";
printf("After assigning: %s\n",p);
}
Output
Before assigning: hello javatpoint
After assigning: hello
Get and puts in c:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
C String Functions
There are many important string functions
defined in "string.h" library.

No Function Description
.
1) strlen(string_name) returns the length of
string name.
2) strcpy(destination, copies the contents of
source) source string to
destination string.
3) strcat(first_string, concats or joins first string
second_string) with second string. The
result of the string is
stored in first string.
4) strcmp(first_string, compares the first string
second_string) with second string. If both
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;
}
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;
}

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() fu
nction.
#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
C Math Functions
There are various methods in math.h header
file. The commonly used functions of math.h
header file are given below.
C Math Example
Let's see a simple example of math
functions found in math.h header file.
#include<stdio.h>
#include <math.h>
int main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
Output:
4M
Netflix Crashed After ‘Stranger Things 4’
Volume 2 Was Released
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12

You might also like