Sie sind auf Seite 1von 12

STRINGS

#include <stdio.h>

#include <string.h>

main()

char name[] = {'a' , 'n' , 'k' , 'i' , 't' , 'a' , '\0'};

char n[] = "ankita";//BOTH THESE INITALIZATIONS ARE VALID

printf("%s %s" , name , n);

A string constant is a one-dimensional array of characters


terminated by a null ( ‘\0’ ).
Both operators have the same precedence, and right-left associativity. This means
the expression will be grouped ++(*ptr) . The ++ part will be applied to the value of the
*ptr part.(++*ptr and *ptr++)

ASCII value of

‘\0’ is 0, whereas ASCII value of ‘0’ is 48.

TO PRINT A STRING USING POINTERS:

main()
{

char name[ ] = "Klinsman" ;


char *ptr ;

ptr = name ; /* store base address of string */


while ( *ptr != '\0' )
{
printf ( "%c", *ptr ) ;
ptr++ ;
}

scanf( ) is not capable of receiving multi-word strings.


Therefore names such as ‘Debashish Roy’ would be
unacceptable. The way to get around this limitation is by
using the function gets( ). The usage of functions gets( ) and
its counterpart puts( ) is shown below.
main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
If we are prepared to take the trouble we can make scanf( )
accept multi-word strings by writing it in this manner:
char name[25] ;
printf ( "Enter your full name " ) ;
scanf ( "%[^\n]s", name );
scanf(“%[ ABC…….Z]” , line);//capital letters and spaces
stops when the first non-matching character is reached
IF ^ IS USED AT THE BEGINNING, IT SPECIFIES ALL CHARACTERS EXCEPT THAT ONE.

THIS FORMAT SPECIFICATION IS KNOWN AS EDIT SET CONVERSION CODE.

char m[09];//will return error as it is octal

char n1[] = "123";


printf("%d is the size of the first string \n" , sizeof(n1));

IT WILL GIVE 4 AS THERE ARE THREE CHARACTERS PLUS NULL TERMINAL


CHARACTER WHICH ALSO OCCUPIES ONE BYTE.
Pointers and Strings
Suppose we wish to store “Hello”. We may either store it in a
string or we may ask the C compiler to store it at some location in
memory and assign the address of the string in a char pointer. This
is shown below:
char str[ ] = "Hello" ;
char *p = "Hello" ;
There is a subtle difference in usage of these two forms. For
example, we cannot assign a string to another, whereas, we can
assign a char pointer to another char pointer. This is shown in the
following program.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to
another set of characters. Unlike strings, such an operation is
perfectly valid with char pointers.
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}

int main(void){
char str1[] = "Hello" ;
//char str2[10] ;
char *s = "Good Morning" ;
char *q ;

//str2 = str1 ; /* error */


q = s ; /* works */
printf("%s" , q);//while printing strings we need the address of the starting character
return 0;
}
In the first call to the function strlen( ), we are passing
the base address of the string, and the function in turn returns the
length of the string. While calculating the length it doesn’t count
‘\0’.

“a” versus ‘a’


– ‘a’ is a single character value (stored in 1 byte) as the ASCII
value for the letter, a
– “a” is an array with two characters, the first is a, the second
is the character value \0
printf("%c", "hello"[1]); WILL PRINT e

IT IS NOT POSSIBLE TO DIRECTLY ASSIGN A STRING TO ANOTHER, ESPECIALLY ONE THAT HAS
BEEN INITIALISED ALREADY. IF THE STRING IS UNINITIALIZED, THEN IT CAN BE DONE AS
FOLLOWS USING POINTERS.

char *str1 = "hello"; /* str1 unchangeable */


char *str2 = "goodbye"; /* str2 unchangeable */
char *str3; /* Not tied to space */
str3 = str1; /* str3 points to same space s1 connected to */

printf("%s %s %s ", str1 , str2 , str3);


printf("%u %u %u " , str1 , str2 , str3);
str3 = str2;

printf("%s %s %s ", str1 , str2 , str3);


printf("%u %u %u " , str1 , str2 , str3);

THIS WILL GIVE THE FOLLOWING OUTPUT:

hello goodbye hello 4206628 4206634 4206628 hello goodbye goodbye 4206628 4206634
4206634
Important to retain end-of-string marker
(replacing str1[5] in the
original string with something other than ‘\0’
makes a string that
does not end)
TO READ A STRING CHARACTER BY
CHARACTER

char line[81], ch;


int c=0;
:
:
do
{
ch = getchar();
line[c] = ch;
c++;
}
while (ch != ‘\n’);
c = c – 1;
line[c] = ‘\0’;
//terminating the string properly
char LastName[11];
char FirstName[11];
printf("Enter your name (last ,
first): ");
scanf("%10s%*[^,],%10s", LastName,
FirstName);
printf("Nice to meet you %s %s\n",
FirstName, LastName);

OUTPUT:

Enter your name (last , first):


RADHAKRISHNAN, ANKITA
Nice to meet you ANKITA RADHAKRISH

strcpy()
• Works very much like a string assignment
operator.
char *strcpy (char *str1, char *str2);
– Assigns the contents of str2 to str1.
– Returns address of the destination string.

strlen()
• Counts and returns the number of characters
in a string.
int strlen (char *str);
len = strlen (string);
/* Returns an integer */
– The null character (‘\0’) at the end is not counted.
– Counting ends at the first null character.

char line[45];
char name[] = "ankita radhakrishnan";
printf("%d is the size of %s " , sizeof(name) , name);
printf("%d is the size of %s " , strlen(name) , name);
printf("\n%u %u\n" , name, line);
printf("%u\n" , strcpy(line, name));

OUTPUT
21 is the size of ankita radhakrishnan 20 is the size of ankita radhakrishnan
6356686 6356707
6356707

strcmp()
• Compares two character strings.
int strcmp(char *str1, char *str2);
– Compares the two strings and returns 0 if they
are identical; non-zero otherwise.

Actually, the function returns the difference in


ASCII values of the first letter of mismatch.
– Less than 0
• If the ASCII value of the character they differ at is smaller for str1,
or str2 is longer than str1(ALWAYS RETURNS -1 IN THIS CASE)
– Greater than 0
• If the ASCII value of the character they differ at is greater for str1,
or str1 is longer than str2(ALWAYS RETURNS +1 IN THIS CASE)
– Equal to 0
• If the two strings are identical

Sometimes we only want to compare first n chars:


int strncmp(char *s1, char *s2, int n)
Works the same as strcmp except that it stops at the nth character
looks at less than n characters if either string is shorter than n
strcmp(“some diff”,”some DIFF”) -- returns value > 0
strncmp(“some diff”,”some DIFF”,4) -- returns 0
String Comparison (ignoring case)
int strcasecmp(char *str1, char *str2)
• similar to strcmp except that upper and lower case
characters (e.g., ‘a’ and ‘A’) are considered to be equal
int strncasecmp(char *str1, char *str2, int n)
• version of strncmp that ignores case
char line[45];

char name[] = "ankita radhakrishnan";

printf("%d" , strncmp("hello","helly" , 4));


printf("%d" , strncmp("hellyi","helly" , 7));
printf("%d" , strncmp("hello","helly" , 6));
printf("%d" , strncasecmp("hellO","hello" , 6));
printf("%d" , strcasecmp("hellO","HEllo"));
OUTPUT:
01-100
IT DOES NOT LOOK AT THE SUBSCRIPT IF IT EXCEEDS THE NUMBER OF
CHARACTERS BUT RETURNS THE NORMAL VALUE OF STRCPY()
strcat()
• Joins or concatenates two strings together
char *strcat (char *str1, char *str2);
– str2 is appended to the end of str1.
– The null character at the end of str1 is removed,
and str2 is joined at that point.
– str1 should have enough space
Searching for a Character/String
char *strchr(char *str, int ch)
• returns a pointer (char *) to the first occurrence of ch in
str
• returns NULL if ch does not occur in str
• can subtract original pointer from result pointer to
determine which character in array is ch
char *strstr(char *str, char *searchstr)
• similar to strchr, but looks for the first occurrence of the
string searchstr in str
char *strrchr(char *str, int ch)
• similar to strchr except that the search starts from the end
of string str and works backward
ALL RETURN POINTERS OF char TYPE
char name[] = "ankita radhakrishnan";

char *p = strchr(name ,'s');//prints 15


printf("it is character %d" , p-name);//this will return the array index of
that character and if it is not present we’ll get garbage value

char line[45];

char name[] = "ankita radhakrishnan";


char srch[] = "nkita";
char *p = strstr(name ,srch);
printf("the starting address of %s is %d" , srch , p-name);
the starting address of nkita is 1
char line[45];

char name[] = "ankita radhakrishnan";


// char srch[] = "rerer";
char *p = strrchr(name ,'a');
printf("the last occurence is %d" , p-name);

the last occurence is 18

Printing to a String
• The sprintf function allows us to print to a string
argument using printf formatting rules
• First argument of sprintf is the string to print to,
remaining arguments are as in printf

char buffer[100];
sprintf (buffer, "%s %s %s %d %f", LastName, FirstName , "12-02-1993" , 26 ,
9.75);
printf("%s" , buffer);
if (strlen(buffer) > 15)
printf("Long name %s %s\n", FirstName, LastName);

Enter your name (last , first): malik , zayn


malik zayn 12-02-1993 26 9.750000Long name zayn malik

Reading from a String


• The sscanf function allows us to read from a string
argument using scanf rules
• First argument of sscanf is the string to read from,
remaining arguments are as in scanf
char buff[100] ="A10 50.0";
char ch;int inum; float fnum;

sscanf(buff,"%c%d%f" , &ch , &inum , &fnum);


printf("%s" , buff);

printf("%c %d %f" , ch, inum , fnum);

A10 50.0A 10 50.000000

strtok() function
char name[45];
scanf("%[^\n]s" , name);

const char s[2] = " ";


char *token;

/* get the first token */


token = strtok(name, s);

/* walk through other tokens */


while( token != NULL ) {
printf( " %s\n", token );

token = strtok(NULL, s);


}

LIST OF INBUILT INT, CHAR VALIDATION FUNCTIONS IN C PROGRAMMING


LANGUAGE:
 “ctype.h” header file support all the below functions in C language. Click on
each function name below for detail description and example programs.

Functions Description

isalpha() checks whether character is alphabetic

isdigit() checks whether character is digit

isalnum() Checks whether character is alphanumeric

isspace() Checks whether character is space

islower() Checks whether character is lower case

isupper() Checks whether character is upper case

isxdigit() Checks whether character is hexadecimal

iscntrl() Checks whether character is a control character

isprint() Checks whether character is a printable character

ispunct() Checks whether character is a punctuation

isgraph() Checks whether character is a graphical character

tolower() Checks whether character is alphabetic & converts to lower case

toupper() Checks whether character is alphabetic & converts to upper case

isdigit(int) – to check if it’s a digit

Das könnte Ihnen auch gefallen