Computer Programming | Education

C Programming | Character Strings


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

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.

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)*/

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

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);

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);

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);
}

4 Comments

  1. Normally I do not read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice post.

  2. Thanks alot : ) for your post. I’d prefer to say that the expense of car insurance differs a lot from one insurance plan to another, due to the fact there are so many different facets which bring about the overall cost. Such as, the model and make of the car or truck will have a tremendous bearing on the charge. A reliable aged family vehicle will have a less expensive premium than just a flashy sports vehicle.

Leave a Reply to Shoshana Snoozy Cancel reply