Skip to main content

Strings in C

Strings are defined as an array of characters. 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.
charstr_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 “cek”.
1. charstr[] = "cek";
2. charstr[50] = "cek";
3. charstr[] = {'c','e',,'k' ,'\0'};
4. charstr[4] = {'c','e','k','\0'};
String input output:printf and scanf with %s format specifier is used for printing and reading. However basic scanf statement will read up to space.The gets(s) function can be used to read a line and store it in string.
Various string handling functions defined in C can be used by including the header file string.h
The most commonly used functions in the string library are:
strcat - concatenate two strings.
strchr - string scanning operation.
strcmp - compare two strings.
strcpy - copy a string.
strlen - get string length.
strncat - concatenate one string with part of another.
strncmp - compare parts of two strings.
strncpy - copy part of a string.
strrchr - string scanning operation.
strstr - Find a substring.
strlwr-convert string to lower case.
strupr-convert string to upper case.
strrev-reverse a string

No standard operators for string assignment and comparison ( like in Python or Java). Strings in C are just arrays of characters only.
Sample Programs
// C program to read and print a string

#include<stdio.h>
int main()
{  
    // declaring string
charstr[50];

    // reading string
scanf("%s",str);

    // print string
printf("%s",str);

return 0;
}
// read a string and print the characters in backwards
#include<stdio.h>
#include<string.h>
int main() {

char S[100];
int l, i;
printf(‘enter the string..\n”);
gets(S);
  l = strlen(S);

printf("\nbackward\n");
for (i = l-1; i >= 0; --i)
printf(" %c",S[i]);
}
//check whether the given string is palindrome
#include<stdio.h>
#include<string.h>
int main() {

char s[100],rs[100];
int l, i;
printf(‘enter the string..\n”);
gets(s);
strcpy(rs,s); // copying the string s to rs using strcpy function
 //reversing the string using built in function strrev
strrev(rs)
 //comparing the strings using strcmp function
If ( strcmp(s,rs)==0)
printf(“String is palindrome”)
else
printf(“Not palindrome”);
}

Caution with string 
 gets is deprecated because it's dangerous, it may cause buffer overflow.
instead of gets you can also use scanf("%[^\n]",s); for reading a string s.Other choices are getline and fgets.
check the following sample program.

Count the occurrence of a character in a string
#include <stdio.h>
#include <string.h>
main()
{
char s[100],c;
int i,n=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c);  // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) n++;
printf("Number of occurrence=%d\n",n);
}

programs to try
1.Toggle the case of every alphabet in the input string.
2. Abbreviate a given string ( print first letter of each word).
3.Read a string print the occurrence of a character.
4.Read a string and count the number of vowels.
5.Print the frequency of occurrence of each vowel character.
6.Remove blank spaces from a string.
7.Count the number of words.
8.Print a substring ( read position and length)
9.Print number of words, vowels and consonants from a given string.
10.Count all the occurrence of a  particular word.
11.Remove all occurrence of  a word from a sentence.
12.Insert a word before a particular word.
13.Check whether a word is present in a string.
14.Read a word and print the characters in alphabetical order.
15.Read list of names and sort the names in alphabetical order.

Comments

  1. hey friends i found a new proagraing language learn php

    ReplyDelete
  2. hey friends i found a new proagraing language learn php

    ReplyDelete

Post a Comment

Popular posts from this blog

Files in C

A file is a repository of data that is stored in a permanent storage media, mainly in secondary memory. In order to use the files we should learn how to read information from a file and how to write information into a file. A very important concept in C is the stream.The stream is a common logical interface to the various devices( files).A stream is linked to a file while using an open operation. A stream is disassociated from a file while using a close operation. The current location, also referred to as the current position, is the location in a file where the next fie access will occur.There are two types of streams text and binary. The following are some difference between text and binary files ·Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable. ·A newline(\n) character is converted into the carriage return-linefeed combination before being written to the d…

KTU C programming question paper and evaluation scheme

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY SECOND SEMESTER B.TECH DEGREE EXAMINATION, MAY 2017 CS 100 COMPUTER PROGRAMMING (CS, IT) SCHEME OF EVALUATION
PART A 1 An identifier is a sequence of characters invented by the programmer or to identify or name a specific object. The sequence of characters may be letters, digits, and special character ‘_’known as an underscore Rules: i)Identifiers should start with alphabets. ii)Identifiers are case sensitive iii)A numeric digit should not be the first character iv)Identifier name should not be a keyword v)Identifier may be of any reasonable length 1mark






2mark 2 Associativity defines the direction, left to right or right to left in which operator act upon its operands Unary operators have associativity is from right to left. For examplein the expression &--x, pre decrement works first and then address of operator works Direction + example<

Linear and Binary Search in C

Searching is one of the most common problems that arise in computing. Searching is the algorithmic process of finding a particular item in a collection of items. A search typically answers either True or False as to whether the item is present. On occasion it may be modified to return where the item is found. Search operations are usually carried out on a key field. Consider searching for a given value k in an array A of size n. There are 2 basic approaches: sequential search and binary search.
Linear (Sequential) Search When data items are stored in a collection such as a list or array , we say that they have a linear or sequential relationship. Each data item is stored in a position relative to the others. In C array, these relative positions are the index values of the individual items. Since these index values are ordered, it is possible for us to visit them in sequence. This process gives rise to our first searching technique, the sequential search. Starting at the first item in …