Strings Adapted from Dr. Mary Eberlein, UT Austin.

Slides:



Advertisements
Similar presentations
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
C programming---String. String Literals A string literal is a sequence of characters enclosed within double quotes: “hello world”
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CS1061 C Programming Lecture 15: More on Characters and Strings A. O’Riordan, 2004.
Computer Science 210 Computer Organization Strings in C.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
1 Chapter 10 Characters, Strings, and the string class.
Introduction to C programming
Strlen() implementation /* strlen : return length of string s */ int strlen(char *s) { int n; for (n = 0 ; s[n] != ‘\0’ ; n++) ; return n; } /* strlen.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Characters, Strings, And The string Class Chapter 10.
Chapter 8: Character and String CMPD144: Programming 1.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
Characters and Strings
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
Today’s Material Strings Definition Representation Initialization
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Strings CSCI 112: Programming in C.
INC 161 , CPE 100 Computer Programming
ECE Application Programming
C Characters and Strings
Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Command Line Arguments
Characters, C-Strings, and More About the string Class
Complex Data Types: Arrays & Structs Topic 7
CSE 303 Lecture 14 Strings in C
Exercises on String Operations
Computer Science 210 Computer Organization
Arrays in C.
Chapter 12: More on C-Strings and the string Class
Standard Version of Starting Out with C++, 4th Edition
Computer Science 210 Computer Organization
Lecture 8b: Strings BJ Furman 15OCT2012.
CSE1320 Strings Dr. Sajib Datta
Lecture 11 Strings.
EECE.2160 ECE Application Programming
String manipulation string.h library
Standard Version of Starting Out with C++, 4th Edition
EECE.2160 ECE Application Programming
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings in C Array of characters is called a string.
Strings #include <stdio.h>
C Characters and Strings
EECE.2160 ECE Application Programming
Presentation transcript:

Strings Adapted from Dr. Mary Eberlein, UT Austin

Character Arrays Strings are represented as arrays of characters The end of the string is specified with '\0' (aka null character) "hello" is represented with array {'h', 'e', 'l', 'l', 'o', '\0'} Examples: char myString[] = "hello"; char myString[10] = "hello"; char myString[] = {'h', 'e', 'l', 'l', 'o', '\0'}; Read about char type and ctype.h functions in textbook. More in recitation.

String Variables A "string" in C is a one-dim array of chars Array length accounts for null character at end #define STR_LEN 80 char str[STR_LEN+1]; If string initializer does not fill array, remaining elements filled with null char ('\0') char date[9] = "June 14"; 0 1 2 3 4 5 6 7 8 C doesn't support strings – it's lower level than other languages. Though extension libraries do give you string functions. Instead: array of characters C doesn't track length of string. The sentinel character \0 at end tells you when end of char array is reached. Make array big enough to include \0 date 'J' 'u' 'n' 'e' '1' '4' '\0'

Reading strings char name[10]; printf("Enter your name: "); scanf("%9s", name); Don't exceed array's bounds Leave room for null character at end of string name is the address of the array Output: Enter your name: FranTarkenton name: FranTarke

Accessing the Characters Function that counts and returns the number of spaces in a given argument string: int countSpaces(const char s[]) { int count, i; count = 0; for(i = 0; s[i] != '\0'; i++) { if(s[i] == ' ') count++; } return count; Can't change s

Comparing Strings Functions in header file string.h are used for string operations Cannot compare two strings with == int strcmp(char s[], char t[]) compares two strings in dictionary (lexicographic) order capital letters less than lowercase letters Returns negative if s comes before t Returns 0 if s is the same string as t Returns positive if s comes after t Examples: strcmp("Abe", "abe") // value is negative strcmp("123", "123") // value is 0 strcmp compares strings lexographically

String Manipulation: Copy & Concatenation strcpy(str1, str2): copies str2 into str1 does not check that str1 is long enough to hold str2! char str1[10], str2[10]; strcpy(str2, "abcd"); // str2 contains "abcd" strcpy(str1, str2); //str1 contains "abcd" strncpy(str1, str2, n): copies up to n characters strcat(str1, str2): appends contents of str2 to end of str1 doesn't check that str1 is long enough strncat(str1, str2, n): appends up to n characters You can never put an array on the left side of an assignment. More about this later. Doesn't work: str2 = "abcd";

String Copy Output: char s[10] = "help"; char *foo = "War of the worlds"; strncpy(s, foo, 9); // copy 9 chars into positions 0-8 printf("s is %s\n, s); printf("length of s: %lu\n", strlen(s)); printf("Last char in s: %d\n", s[9]); Output: s is War of th length of s: 9 Last char in s: 0

strlen Function strlen(str): returns length of string stored in array str (not including null character at end) int len; char str[10] = "abc"; len = strlen(str); // len is 3

Search for chars and substrings char *strchr(s, ch): returns pointer to first occurrence of ch in s, or NULL if ch is not found in s char *strstr(s1, s2): returns a pointer to first occurrence of s2 in s1

Useful Functions (stdlib.h) Description double atof(const char str[]) Converts string str to a double int atoi(const char str[]) Converts string str to an int double strtod(const char str[], char **endptr) Converts str to double (and returns the double), endptr points to the next character in str after the numerical value int abs(int x) returns the absolute value of integer x Also: int abs(int x): returns absolute value of an INT

Example Output: char str[10] = "3.14 This is pi"; char *restOfString; double num; num = strtod(str, &restOfString); printf("The number is %lf\n", num); printf("The remaining string: %s\n", restOfString); Output: The number is 3.140000 The remaining string: This is pi

Example Other useful character handling functions in ctype.h: see 23.5, p. 612 isalnum(c) : is c alphanumeric? isalpha(c): is c alphabetic? isdigit(c): is c a decimal digit? islower(c): is c a lower-case letter? toupper(c): returns uppercase version of c if it's a letter, c otherwise #include<stdio.h> #include<ctype.h> #include<stdlib.h> ... // Q for queen, 10, 9, etc. char cardValue[3]; puts("Enter your card's value: "); scanf("%2s", cardValue); if(isdigit(cardValue[0])) { int value = atoi(cardValue); printf("Value: %d\n", value); } If card is 2, ..., 10, the value will be converted to an int and printed. If it's a J, Q, K, or A, it will not.

Command Line Arguments

Input on command line int main(int argc, char* argv[]) {…} argc: # of arguments on command line includes name of executable argv[]: array of strings on command line

Example Sample Run: int main(int argc, char *argv[]) { for(int i = 0; i < argc; i++) { printf("arg %d = %s\n", i, argv[i]); } Sample Run: bash-3.2$ gcc commLine.c bash-3.2$ ./a.out one two three arg 0 = ./a.out arg 1 = one arg 2 = two arg 3 = three

Command Line Args Output? Note: argv[0] is ./prog argv[1] is 4 int main(int argc, char *argv[]) { if(argc < 2) printf("Need an integer!"); else { int n = atoi(argv[1]); int nums[n]; // legal in C99 for(int i = 0; i < n; i++) } nums[i] = i; } for(int i = 0; i < n; i += 2) printf("%d\n", nums[i]); Output? % gcc –o prog prog.c % ./prog 4 atoi() Note that loop update increments by 2. First loop creates nums[4] containing 0-3 Second loop prints nums[0], nums[2], i.e., 0 and 2 Note: argv[0] is ./prog argv[1] is 4

Exercise Write a program that takes integers on the command line and prints their sum. You may assume that all the command line arguments other than the executable name are integers. Example run: ./a.out 3 5 1 Sum = 9