Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

C Programming – Handling of Character String

By Brian Moriya | on April 17, 2006 |
C Language

In this tutorial you will learn about Initializing Strings, Reading Strings from the terminal, Writing strings to screen, Arithmetic operations on characters, String operations (string.h), Strlen() function, strcat() function, strcmp function, strcmpi() function, strcpy() function, strlwr () function, strrev() function and strupr() function.

In C language, strings are stored in an array of char type along with the null terminating character "\0" at the end. In other words to create a string in C you create an array of chars and set each element in the array to a char value that makes up the string. When sizing the string array you need to add plus one to the actual size of the string to make space for the null terminating character, “\0”

Syntax to declare a string in C:

  1. 	char fname[4];

The above statement declares a string called fname that can take up to 3 characters. It can be indexed just as a regular array as well.

fname[] = {‘t’,’w’,’o’};

Character t w o \0
ASCII Code 116 119 41 0

The last character is the null character having ASCII value zero.

Initializing Strings

To initialize our fname string from above to store the name Brian,

  1. 	char fname[31] = {"Brian"};

You can observe from the above statement that initializing a string is same as with any array. However we also need to surround the string with quotes.

Writing Strings to the Screen

To write strings to the terminal, we use a file stream known as stdout. The most common function to use for writing to stdout in C is the printf function, defined as follows:

  1. 	int printf(const char *format, ...);

To print out a prompt for the user you can:

  1. 	printf("Please type a name: \n");

The above statement prints the prompt in the quotes and moves the cursor to the next line.

If you wanted to print a string from a variable, such as our fname string above you can do this:

  1. 	printf("First Name: %s", fname);

You can insert more than one variable, hence the “…” in the prototype for printf but this is sufficient. Use %s to insert a string and then list the variables that go to each %s in your string you are printing. It goes in order of first to last. Let’s use a first and last name printing example to show this:

  1. 	printf("Full Name: %s %s", fname, lname);

The first name would be displayed first and the last name would be after the space between the %s’s.

Reading Strings from the Terminal

When we read a string from the terminal we read from a file stream known as stdin. *nix users are probably familiar with this, it’s how you can type a program name into the terminal and pass it arguments also.

Say we want to allow the user to enter a name from stdin. Aside from taking the name as a command line argument, we can use the scanf function which has the following prototype:

  1. 	int scanf(const char *format, ...);

Note the similarity to printf.

Quick example to tie the last few sections together.

getname.c:

  1.  #include <stdio.h>
  2.  
  3. void main() {
  4.  
  5.   char fname[30];
  6.   char lname[30];
  7.  
  8.   printf("Type first name:\n");
  9.   scanf("%s", fname);
  10.  
  11.   printf("Type last name:\n");
  12.   scanf("%s", lname);
  13.  
  14.   printf("Your name is: %s %s\n", fname, lname);
  15. }

We declare two strings fname and lname. Then we use the printf function to prompt the user for a first name. The scanf function takes the input from stdin and automatically exits once the user presses enter. Then we repeat the above sequence except using the last name this time. Finally we print the full name that was typed back to stdout. Should look something like this:

Arithmetic Operations on Strings

Characters in C can be used just like integers when used with arithmetic operators. This is nice, for example, in low memory applications because unsigned chars take up less memory than do regular integers as long as your value does not exceed the rather limited range of an unsigned char.

Let us cut to our example,

charmath.c:

  1. 	 #include <stdio.h>
  2. 	void main() {
  3. 	  unsigned char val1 = 20;
  4. 	  unsigned char val2 = 30;
  5. 	  int answer;
  6.  
  7. 	  printf("%d\n", val1);
  8. 	  printf("%d\n", val2);
  9.  
  10. 	  answer = val1 + val2;
  11. 	  printf("%d + %d = %d\n", val1, val2, answer);
  12.  
  13. 	  val1 = 'a';
  14. 	  answer = val1 + val2;
  15.  
  16. 	  printf("%d + %d = %d\n", val1, val2, answer);
  17. 	}

First we make two unsigned character variables and give them (rather low) number values. We then add them together and put the answer into an integer variable. We can do this without a cast because characters are an alphanumeric data type. Next we set var1 to an expected character value, the letter lowercase a. Now this next addition adds 97 to 30, why?

Because the ASCII value of lowercase a is 97. So it adds 97 to 30, the current value in var2. Notice it did not require casting the characters to integers or having the compiler complain. This is because the compiler knows when to automatically change between characters and integers or other numeric types.

String Operations

Character arrays are a special type of array that uses a “\0” character at the end. As such it has it is own header library called string.h that contains built-in functions for performing operations on these specific array types.

You must include the string header file in your programs to utilize this functionality.

  1. 	 #include <string.h>

We will cover the essential functions from this library over the next few sections.

Length of a String

Use the strlen function to get the length of a string minus the null terminating character.

  1. 	int strlen(string);

If we had a string, and called the strlen function on it we could get its length.

  1. 	char fname[30] = {"Bob"};
  2. 	int length = strlen(fname);

This would set length to 3.

Concatenation of Strings

The strcat function appends one string to another.

  1. 	char *strcat(string1, string2);

The first string gets the second string appended to it. So for example to print a full name from a first and last name string we could do the following:

  1. 	char fname[30] = {"Bob"};
  2. 	char lname[30] = {"by"};
  3. 	printf("%s", strcat(fname, lname));

The output of this snippet would be “Bobby.”

Compare Two Strings

Sometimes you want to determine if two strings are the same. For this we have the strcmp function.

  1. 	int strcmp(string1, string2);

The return value indicates how the 2 strings relate to each other. if they are equal strcmp returns 0. The value will be negative if string1 is less than string2, or positive in the opposite case.

For example if we add the following line to the end of our getname.c program:

  1. 	printf("%d", strcmp(fname, lname));

When run on a Linux computer with the following first and last name combinations, the program will yield the following output.

  1. 	First name: Bob, last name: bob, output: -1.
  2. 	First name: bob, last name: Bob, output 1.
  3. 	First name: Bob, last name: Bob, output 0.

Compare Two Strings (Not Case Sensitive)

If you do not care whether your strings are upper case or lower case then use this function instead of the strcmp function. Other than that, it’s exactly the same.

  1. 	int strcmpi(string1, string2);

Imagine using this function in place of strcmp in the above example, all of the first and last combinations would output 0.

Copy Strings

To copy one string to another string variable, you use the strcpy function. This makes up for not being able to use the “=” operator to set the value of a string variable.

  1. 	strcpy(string1, string2);

To set the first name of our running example in code rather than terminal input we would use the following:

  1. 	strcpy(fname, "Bob");

Converting Uppercase Strings to Lowercase Strings

This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows.

  1. 	strlwr(string);

This will convert uppercase characters in string to lowercase. So “BOBBY” would become “bobby”.

Reversing the Order of a String

This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows.

  1. 	strrev(string);

Will reverse the order of string. So if string was “bobby”, it would become “ybbob”.

Converting Lowercase Strings to Uppercase Strings

This function is not part of the ANSI standard and therefore strongly recommended against if you want your code to be portable to platforms other than Windows.

strupr(string);

This will convert lowercase characters in string to uppercase. So “bobby” would become “BOBBY”.

« « Career Strategies for Women
VB Script Tutorials- Introduction » »

Author Description

Avatar

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • C Programming – Functions (Part-II)

    May 22, 2006 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Programming – An Overview

    March 2, 2006 - 0 Comment
  • C Programming – Functions (Part-I)

    May 23, 2006 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • C Programming – Constants and Identifiers

    March 2, 2006 - 0 Comment
  • C Programming – Structures and Unions

    May 25, 2006 - 0 Comment
  • C Programming – Data Types : Part 1

    March 7, 2006 - 0 Comment
  • C Programming – Pointers

    May 25, 2006 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Programming – Data Types : Part 2

    August 21, 2011 - 0 Comment
  • C Circular Linked Lists

    June 26, 2011 - 0 Comment
  • C Doubly Linked Lists

    June 26, 2011 - 0 Comment
  • TSR in C – An Introduction

    July 11, 2006 - 0 Comment
  • Concept of Pixel in C Graphics

    July 11, 2006 - 0 Comment
  • Call by Value and Call by Reference

    July 6, 2006 - 0 Comment
  • C Language – The Preprocessor

    May 31, 2006 - 0 Comment
  • C Programming – File management in C

    May 31, 2006 - 0 Comment
  • C Programming – Linked Lists

    May 29, 2006 - 0 Comment
  • C Programming – Dynamic Memory allocation

    May 29, 2006 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • C Programming – Data Types : Part 2
  • C Circular Linked Lists
  • C Doubly Linked Lists
  • TSR in C – An Introduction
  • Concept of Pixel in C Graphics

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT