C: Strings

We left off in our last tutorial noticing that the creators of C geared it towards numerics, and made it difficult to handle text in the language. Being a writer, this offends me greatly, and so in this article I will teach you to force C to do you bidding and deal with text.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
March 03, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement
Sure, it will kick and scream. But in the end it'll all be worth it, because you can print the glorious text: “Hello World” to your screen.  

Just a brief warning: if you've been following along in this series, you may see some information repeated from prior articles. Feel free to skip over it if you like. I've included it here as a reference.

Stringing It All Together

Simply put, a string is a group of characters. An example of a string would be a word: it, the, apple, hamburgers; a sentence: I like to eat bacon; and even random characters thrown together: alpha9fzxc1_beefrt. Strings are stored in memory as ASCII codes, representing the characters. C doesn't know its “G” from a hole in the ground. While you don't need to worry about knowing the various ASCII codes, here is a table of the “printable characters”:


Ascii

Character

Ascii

Character

Ascii

Character

32

Space

64

@

96

`

33

!

65

A

97

a

34

66

B

98

b

35

#

67

C

99

c

36

$

68

D

100

d

37

%

69

E

101

e

38

&

70

F

102

f

39

'

71

G

103

g

40

(

72

H

104

h

41

)

73

I

105

i

42

*

74

J

106

j

43

+

75

K

107

k

44

,

76

L

108

l

45

-

77

M

109

m

46

.

78

N

110

n

47

/

79

O

111

o

48

0

80

P

112

p

49

1

81

Q

113

q

50

2

82

R

114

r

51

3

83

S

115

s

52

4

84

T

116

t

53

5

85

U

117

u

54

6

86

V

118

v

55

7

87

W

119

w

56

8

88

X

120

x

57

9

89

Y

121

y

58

:

90

Z

122

z

59

;

91

[

123

{

60

<

92

 

124

|

61

“=”

93

]

125

}

62

>

94

^

126

~

63

?

95

_



Storing Strings

In C, you store strings in arrays, with each letter of the string going into a separate element in the array. Let's say we want to store a name in an array. Let's say the name is really cool and regal...something like: James. Here is how we would create the array to store the value and then access the array to print it out:


#include <stdio.h>


int main ()

{

char name[10]="James";

printf (name);

 

return(0);

}

Here we create an array named “name” and store the string “James” inside of it. Then we use the printf() function to print out the stored value, resulting in:

  James

Storing Strings from User Input

In the following code we will ask the user to enter their first name and then print that name to the screen:


#include <stdio.h>

int main ()

{

char name[10];

printf("Enter your first name ");

gets_s (name);

printf("Your name is %s", name);

return(0);

}

This program creates an array called “name”. It then prints some text asking the user to input their first name. Then it uses the get_s() function to store the data the user enters into the name array. Lastly we print out the value inside name using the printf() function and the %s placeholder.

Note that when assigning the amount of elements in the array, be sure to include one extra for the null terminator (o) that C inserts at the end.

String Operations

There are many string functions in C, and we will discuss a few of them here, starting with the strlen() function. Before we do though, be sure to include the <string.h> library.

Strlen()

If you want to count the amount of characters in a string, you can use the strlen() function.


#include <stdio.h>

#include <string.h>

int main ()

{

char name[80];

int length;

printf("Enter your name: ");

gets_s (name);

length=strlen(name);

printf("nThe name %s contains %d characters, including

spaces.n",name, length);

return(0);

}

This program creates an array capable of holding 79 characters called “name,” and a variable named length. It then prints some text asking the user to enter their name and stores the input in the name array. Next, we use the strlen() function to count the number of characters (including spaces) in the name array, and store it in the variable length. Finally, we print some text displaying the user's name and how many characters are in their name. If the user had input Aunt Jemima as their name, this would be the result:

  Enter your name: Aunt Jemima

  The name Aunt Jemima contains 11 characters, including spaces.

Strcat()

If you wish to concatenate or join two strings together, you can use the strcat() function, like so:


#include <stdio.h>

#include <string.h>

int main ()

{

char first[80]="Yippie";

char second[90]="Hooray";

char spacer[5]="n";

printf(first);

printf(spacer);

strcat_s(first,second);

printf(first);

printf(spacer);

printf(second);

return(0);

}

This program creates three arrays. The first one, aptly named first, stores the value “Yippie.” The second array, named (you guessed it) second, holds the value “Hooray.” The third, titled “Spacer,” is used to insert a blank line between the text we will be printing.

We start off printing the value of first, and then we print out the spacer. Next we use strcat_s() to join the values of first and second together. Note that this value gets stored in first, and the value of second stays the same. We then print out first again, to show its new value, then a spacer, and finally the array second, to show that it has not changed. The result is:

  Yippie

  YippieHooray

  Hooray

Strcmp()

C can't technically compare a string to a string, as it only sees strings as ascii codes. However, there is a function in C called strcmp() that allows you to do so. The function takes two strings and compares the value, returning 0 if they are equal and a non zero number if they are not. To demonstrate, I will show you how to create a program to insult someone named James:


#include <stdio.h>

#include <string.h>

int main ()

{

char insult[10];

printf("Please enter your first name: ");

scanf_s("%s", insult);

if( strcmp (insult, "James") == 0) {

printf( "James is a fat man's name.n");

}

return(0);

}

This program creates an array named insult. It then asks the user to enter their name and stores the value in the insult array. Next we use the strcmp() function to compare the value of insult to “James” and if the result of that comparison equals 0, then it prints some text. If not, nothing happens. Note that the strcmp() function is case sensitive. There are two ways, for this example at any rate, to overcome this. First, we can make the program so it insults anyone, no matter what their name is:


#include <stdio.h>

#include <string.h>

int main ()

{

char insult[10];

printf("Please enter your first name: ");

scanf_s("%s", insult);

if( strcmp (insult, insult) == 0) {

printf( "%s is a fat man's name.n",insult);

}

return(0);

}

This program works similar to the prior one, except now it compares the value of the array insult to itself. So let's say the user entered in the name Guido; the result would be:

  Please enter your name: Guido

  Guido is a fat man's name.

The other way to do it is to use our dear friend, the _strcmpi function, which works in the same manner, but allows for non-case sensitivity.


#include <stdio.h>

#include <string.h>

int main ()

{

char insult[10];

printf("Please enter your first name: ");

scanf_s("%s", insult);

if( _strcmpi (insult, "James") == 0) {

printf( "James is a fat man's name.n");

}

return(0);

}

Strcpy()

To copy one string into another, use the strcpy_s() function. It works by placing the second string into the first:


#include <stdio.h>

#include <string.h>

int main ()

{

char first[10];

char second[10]="James";

strcpy_s(first,second);

printf(first);

return(0);

}

The result of this program is:

  James

While that isn't all of the string functions or ways that you can use strings in C, it should give you a good start. In our next article we will discuss how to use loops in C. So come back soon.

Till then...

blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials