C Programming | Character Strings

Feel free to fill this feedback form to help us improve our content

https://forms.gle/r5fJjWmkqtdLVJr48


Advertisements

What we would learn about strings

  • Representation in C
  • String Literals
  • String Variables
  • String Input/Output ( printf, scanf, gets, fgets, puts, fputs )

Introduction

A string is an array of characters.

  • Individual characters are stored in memory in ASCII code.
  • A string is represented as a sequence of characters terminated by the null (‘\0’) character whose ASCII value is zero

String Literals

String literal values are represented by sequences of characters between double quotes (“)

Examples

  • “” represents empty string
  • “hello”

“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
Advertisements

Referring to String Literals

String literal is an array, can refer to a single character from the literal as a character

Example:

printf(”%c”, ”hello”[1]); 
//outputs the character ‘e’

During compilation, C creates space for each string literal (# of characters in the literal + 1)

Declaring String Variables

A string is declared like any other array:

char string-name [size];
  • size determines the number of characters in string_name.

When a character string is assigned to a character array, it automatically appends the null character (‘\0’) at the end of the string.

  • size should be equal to the number of characters in the string plus one.
Advertisements

Examples

char name[30]; 
char city[15]; 
char dob[11];

A string may be initialized at the time of declaration.

char   city[15] = “Calcutta”; 
char   city[15] = {‘C’, ‘a’, ‘l’, ‘c’, ‘u’, ‘t’, ‘t’, ‘a’}; 
char   dob[] = “12-10-1975”;

Duplicate String Literals

Each string literal in a C program is stored at a different location

So even if the string literals contain the same string, they are not equal (in the == sense)

Example:

char string1[6] = “hello”; 
char string2[6] = “hello”; 
/*but string1 does not equal string2
(they are stored at different locations)*/
Advertisements

Changing String Variables

Cannot change string variables connected to string constants, but can change pointer variables that are not tied to space.

Example:

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 */ 
str3 = str2;

Can change parts of a string variable

char str1[6] = “hello”; 
str1[0] = ‘y’; /* str1 is now “yello” */ 
str1[4] = ‘\0’; /* str1 is now “yell” */

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)

Have to stay within limits of array –responsibility of programmer

Reading Strings from the Keyboard

Two different cases will be considered:

  • Reading words
  • Reading an entire line

Reading words

scanf can be used with the “%s” format specification.

char   name[30]; 
scanf (“%s”, name);

The ampersand (&) is not required before the variable name with “%s”.

  • “name” represents an address
Advertisements

The problem here is that the string is taken to be upto the first white space (blank, tab, carriage return, etc.)

  • If we type “Rupak Biswas”
  • name will be assigned the string “Rupak

Reading a line of text

In many applications, we need to read in an entire line of text (including blank spaces).

We can use the getchar() function for the purpose.

char   line[81], ch; 
int  c=0; 

do { 
  ch = getchar(); 
  line[c] = ch; 
  c++; 
} while (ch != ‘\n’); 
c = c – 1; 
line[c] = ‘\0’;

Reading a line :: Alternate Approach

Reads a string containing uppercase characters and blank spaces

char line[81]; 
scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line);

Reads a string containing any characters until a newline character is received

char line[81]; 
scanf (“%[^\n]”, line);
Advertisements

More on String Input

Edit set input %[ListofChars]

  • ListofChars specifies set of characters (called scan set)
  • Characters read as long as character falls in scan set
  • Stops when first non scan set character encountered
  • Note, does not ignored leading white space
  • Any character may be specified except ]
  • Putting ^ at the start to negate the set (any character BUT list is allowed)

Examples:

scanf (“%[−+0123456789]”, Number); 
scanf (“%[^\n]”,Line);   
/* read until newline char */

Writing Strings to the Screen

We can use printf with the “%s”format specification.

char name[50];
printf (“\n %s”, name);
Advertisements

Input / Output Example

#include <stdio.h>
void main( ) { 
  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);
}

Feel free to fill this feedback form to help us improve our content

https://forms.gle/r5fJjWmkqtdLVJr48

Thanks for reading this article,

Team BloggeBoy

We hope that you have found this article valuable. Please visit some of our recent post to gain lots of information. And feel free to share them with your friends and family.

2 thoughts on “C Programming | Character Strings

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: