Lecture 7
Lecture 7
Lecture 7
CS/CE 224/272
Nadia Nasir
The first element of any array in C is at index 0. The second is at index 1, and so on ...
char s[10];
s[0] = 'h';
s[1] = 'i’;
s[2] = '!'; h i ! \0 ? ? ? ? ? ?
s[3] = '\0';
s in[0]
This notation can be used [1] of
all kinds [2]statements
[3] [4] and
[5]expressions
[6] [7] [8] in C: [9]
For example:
c = s[1];
if (s[0] == '-') …
switch (s[1]) ...
String Literals
char your_line[100];
cout << "Enter a line:\n";
cin.getline (your_line,100);
You can overflow your string buffer, so be careful!
The C String Library
An Example - strncmp
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char str1[] = "The first string.";
char str2[] = "The second string.";
size_t n, x;
cout << strncmp(str1,str2,4) ; // 0
cout << strncmp(str1,str2,5) ; // -1
}
Searching Strings (1)
There are a number of searching functions:
char * strchr (char * str, int ch) ;
strchr search str until ch is found or NULL character is
found instead.
If found, a (non-NULL) pointer to ch is returned.
Otherwise, NULL is returned instead.
You can determine its location (index) in the string by:
Subtracting the value returned from the address of
the start of the string
More pointer arithmetic … more on this later!
Example