The document discusses strings in C++. It defines strings, describes how to declare and manipulate string objects using the string class in C++, and lists common string operations like concatenation, comparison, extracting substrings, searching/finding patterns, and inserting/replacing/deleting substrings. It also discusses how to work with C-style strings using functions in the <strings.h> library and character functions in <ctype.h>.
The document discusses various methods for working with C++ strings, including:
1. Reading strings from the keyboard using getline() and specifying the string size and optional terminating character.
2. Comparing strings using operators like ==, !=, <, <=, >, >=.
3. Accessing individual characters of a string using the index operator [].
4. Obtaining the length of a string using length() or size(), checking if a string is empty, and extracting substrings.
String in programming language in c or c++Azeemaj101
This document discusses strings in C++. It defines a string as a sequence of characters and provides examples. It explains that strings can be represented using C-style character arrays or the C++ string class. When using character arrays, strings are null-terminated and common functions like strcpy(), strcat(), and strlen() are used. The C++ string class provides a safer alternative with useful methods like assign(), append(), insert(), replace(), erase(), find(), and more. It also supports all C++ operators and returns the string length.
This document provides an overview of string manipulation in C++. It discusses C-style strings and introduces C++ strings as objects of the string class. It describes various string constructors, functions for comparison, concatenation, insertion, extraction and other operations. Examples are given to demonstrate the use of functions like length(), capacity(), empty(), at(), find(), assign(), begin() and end(). The document is intended as a lecture on object-oriented string handling in C++.
1) The document discusses C++ strings and the string class. It provides two representations of strings in C++ - C-style character strings and the string class.
2) Functions like strcpy(), strcat(), strlen() etc. can be used to manipulate C-style strings. The string class provides similar and additional functionality.
3) Examples are given to demonstrate declaring and using C-style strings, the string class, and functions to copy, concatenate, get the length of strings. Input from the user is also demonstrated.
The document discusses C strings and the string class in C++. It provides information on:
- C strings being null-terminated character arrays
- Declaring and initializing C string variables
- Common C string functions like strlen(), strcpy(), strcmp()
- The C++ string class which handles memory allocation dynamically and supports operators like + and +=
- Key differences between C strings and the string class like null termination and size handling
The document discusses C++ string methods. It describes functions like append(), at(), begin(), clear(), copy(), empty(), erase(), find(), insert(), replace(), and more. These functions allow manipulating, searching, and modifying string objects and their character contents in C++.
This document provides an overview of common string operations in C++, including how to declare and initialize strings, access individual characters, compare strings, append to strings, search within strings, and convert between C++ strings and C-style character arrays. It also describes some additional string utility functions provided in the CS106 library like converting case and converting between strings and numbers.
The document discusses string operations in C, defining strings as arrays of characters with a null terminator, and covering functions for declaring, initializing, inputting, manipulating, comparing, searching, and copying strings using standard library functions like strlen(), strcpy(), strcmp(), strchr(), and more. It provides examples of using these string functions to declare, compare, concatenate, and copy strings in C code.
Presentation more c_programmingcharacter_and_string_handling_KarthicaMarasamy
The document discusses C string operations like strcpy, strcat, strcmp, and strlen. It provides examples of using each function, including copying one string into another with strcpy, appending strings with strcat, comparing strings alphabetically with strcmp, and getting the length of a string with strlen. It also covers basic string declarations and built-in functions for manipulating characters.
Introduction to Arrays and Strings.pptxDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Chapter 1 Introduction to Arrays and StringsDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. A string is a sequence of characters. In most programming languages, strings are treated as arrays of characters, but they often come with special functionality for manipulation.
String in programming language in c or c++ Samsil Arefin
This document discusses strings in C programming. It defines strings as arrays of characters terminated by a null character. Strings can be declared as character arrays or using string pointers. Functions like strlen(), strcpy(), strcat() are described which operate on strings. Examples are given to find the frequency of characters, number of vowels/consonants, reversing a string, sorting strings, and concatenating strings. The strcat() function is explained in detail, with an example program demonstrating how it concatenates two strings.
This document discusses string handling in C++. It defines a string as a collection of characters written in double quotation marks. Strings can be declared and initialized similarly to character arrays. The cin object and cin.getline() function can be used to input strings with or without spaces. Arrays of strings are two-dimensional character arrays that store multiple strings. Common string functions include memcpy() to copy characters, strcmp() to compare strings, strcpy() to copy one string to another, strlen() to find the length of a string, and strcat() to concatenate two strings.
The document discusses strings in C programming language. It provides details about:
- Strings are arrays of characters terminated by a null character '\0'.
- Common functions to declare, initialize, print and manipulate strings like strlen(), strcpy(), strcat(), strcmp() etc.
- Important points about receiving and processing multi-word strings using scanf(), gets() and puts().
- Implementation of some string handling functions like xstrlen(), xstrcpy() to demonstrate their working.
The document discusses strings in C and common string functions. It defines a string as an array of characters terminated by a null character. It describes two ways to use strings - with a character array or string pointer. It then explains functions such as strcpy(), strcat(), strcmp() that copy, append, or compare strings. Other functions like memcpy(), memcmp() operate on a specified number of characters rather than null-terminated strings.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
The document is a slide presentation on strings in C++. It covers topics like the concept of strings as character arrays, string manipulation functions from the string handling library like strcpy(), strcat(), strcmp(), and examples of using these functions. It also discusses fundamentals of characters and strings, comparing strings, and common errors with strings. The presentation is delivered by Dr. Ali Mirza of the Computer Science department at Bahria University for their CSC 113 computer programming course.
watch a video here for beginneers
in c++ programming language
https://www.youtube.com/channel/UCThawdb6qPuk3wkCtinhLDg
The document discusses C strings and the string class in C++. It provides information on:
- C strings being null-terminated character arrays
- Declaring and initializing C string variables
- Common C string functions like strlen(), strcpy(), strcmp()
- The C++ string class which handles memory allocation dynamically and supports operators like + and +=
- Key differences between C strings and the string class like null termination and size handling
The document discusses C++ string methods. It describes functions like append(), at(), begin(), clear(), copy(), empty(), erase(), find(), insert(), replace(), and more. These functions allow manipulating, searching, and modifying string objects and their character contents in C++.
This document provides an overview of common string operations in C++, including how to declare and initialize strings, access individual characters, compare strings, append to strings, search within strings, and convert between C++ strings and C-style character arrays. It also describes some additional string utility functions provided in the CS106 library like converting case and converting between strings and numbers.
The document discusses string operations in C, defining strings as arrays of characters with a null terminator, and covering functions for declaring, initializing, inputting, manipulating, comparing, searching, and copying strings using standard library functions like strlen(), strcpy(), strcmp(), strchr(), and more. It provides examples of using these string functions to declare, compare, concatenate, and copy strings in C code.
Presentation more c_programmingcharacter_and_string_handling_KarthicaMarasamy
The document discusses C string operations like strcpy, strcat, strcmp, and strlen. It provides examples of using each function, including copying one string into another with strcpy, appending strings with strcat, comparing strings alphabetically with strcmp, and getting the length of a string with strlen. It also covers basic string declarations and built-in functions for manipulating characters.
Introduction to Arrays and Strings.pptxDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Chapter 1 Introduction to Arrays and StringsDawitTekie1
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. A string is a sequence of characters. In most programming languages, strings are treated as arrays of characters, but they often come with special functionality for manipulation.
String in programming language in c or c++ Samsil Arefin
This document discusses strings in C programming. It defines strings as arrays of characters terminated by a null character. Strings can be declared as character arrays or using string pointers. Functions like strlen(), strcpy(), strcat() are described which operate on strings. Examples are given to find the frequency of characters, number of vowels/consonants, reversing a string, sorting strings, and concatenating strings. The strcat() function is explained in detail, with an example program demonstrating how it concatenates two strings.
This document discusses string handling in C++. It defines a string as a collection of characters written in double quotation marks. Strings can be declared and initialized similarly to character arrays. The cin object and cin.getline() function can be used to input strings with or without spaces. Arrays of strings are two-dimensional character arrays that store multiple strings. Common string functions include memcpy() to copy characters, strcmp() to compare strings, strcpy() to copy one string to another, strlen() to find the length of a string, and strcat() to concatenate two strings.
The document discusses strings in C programming language. It provides details about:
- Strings are arrays of characters terminated by a null character '\0'.
- Common functions to declare, initialize, print and manipulate strings like strlen(), strcpy(), strcat(), strcmp() etc.
- Important points about receiving and processing multi-word strings using scanf(), gets() and puts().
- Implementation of some string handling functions like xstrlen(), xstrcpy() to demonstrate their working.
The document discusses strings in C and common string functions. It defines a string as an array of characters terminated by a null character. It describes two ways to use strings - with a character array or string pointer. It then explains functions such as strcpy(), strcat(), strcmp() that copy, append, or compare strings. Other functions like memcpy(), memcmp() operate on a specified number of characters rather than null-terminated strings.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
The document is a slide presentation on strings in C++. It covers topics like the concept of strings as character arrays, string manipulation functions from the string handling library like strcpy(), strcat(), strcmp(), and examples of using these functions. It also discusses fundamentals of characters and strings, comparing strings, and common errors with strings. The presentation is delivered by Dr. Ali Mirza of the Computer Science department at Bahria University for their CSC 113 computer programming course.
watch a video here for beginneers
in c++ programming language
https://www.youtube.com/channel/UCThawdb6qPuk3wkCtinhLDg
The document discusses operating systems, describing their core functions like managing programs, memory, and tasks. It covers the startup and shutdown processes, user interfaces, and configuration options. Specific desktop operating systems are examined, including Windows, Mac OS, Linux, and Chrome OS. Server operating systems and mobile operating systems are also overviewed, highlighting examples like Android, iOS, and Windows Phone. The chapter provides information on operating system features across different categories of devices.
Neural representations have shown the potential to accelerate ray casting in a conventional ray-tracing-based rendering pipeline. We introduce a novel approach called Locally-Subdivided Neural Intersection Function (LSNIF) that replaces bottom-level BVHs used as traditional geometric representations with a neural network. Our method introduces a sparse hash grid encoding scheme incorporating geometry voxelization, a scene-agnostic training data collection, and a tailored loss function. It enables the network to output not only visibility but also hit-point information and material indices. LSNIF can be trained offline for a single object, allowing us to use LSNIF as a replacement for its corresponding BVH. With these designs, the network can handle hit-point queries from any arbitrary viewpoint, supporting all types of rays in the rendering pipeline. We demonstrate that LSNIF can render a variety of scenes, including real-world scenes designed for other path tracers, while achieving a memory footprint reduction of up to 106.2x compared to a compressed BVH.
https://arxiv.org/abs/2504.21627
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfällepanagenda
Webinar Recording: https://www.panagenda.com/webinars/domino-iq-was-sie-erwartet-erste-schritte-und-anwendungsfalle/
HCL Domino iQ Server – Vom Ideenportal zur implementierten Funktion. Entdecken Sie, was es ist, was es nicht ist, und erkunden Sie die Chancen und Herausforderungen, die es bietet.
Wichtige Erkenntnisse
- Was sind Large Language Models (LLMs) und wie stehen sie im Zusammenhang mit Domino iQ
- Wesentliche Voraussetzungen für die Bereitstellung des Domino iQ Servers
- Schritt-für-Schritt-Anleitung zur Einrichtung Ihres Domino iQ Servers
- Teilen und diskutieren Sie Gedanken und Ideen, um das Potenzial von Domino iQ zu maximieren
In this talk, Elliott explores how developers can embrace AI not as a threat, but as a collaborative partner.
We’ll examine the shift from routine coding to creative leadership, highlighting the new developer superpowers of vision, integration, and innovation.
We'll touch on security, legacy code, and the future of democratized development.
Whether you're AI-curious or already a prompt engineering, this session will help you find your rhythm in the new dance of modern development.
Trends Artificial Intelligence - Mary MeekerClive Dickens
Mary Meeker’s 2024 AI report highlights a seismic shift in productivity, creativity, and business value driven by generative AI. She charts the rapid adoption of tools like ChatGPT and Midjourney, likening today’s moment to the dawn of the internet. The report emphasizes AI’s impact on knowledge work, software development, and personalized services—while also cautioning about data quality, ethical use, and the human-AI partnership. In short, Meeker sees AI as a transformative force accelerating innovation and redefining how we live and work.
Your startup on AWS - How to architect and maintain a Lean and Mean account J...angelo60207
Prevent infrastructure costs from becoming a significant line item on your startup’s budget! Serial entrepreneur and software architect Angelo Mandato will share his experience with AWS Activate (startup credits from AWS) and knowledge on how to architect a lean and mean AWS account ideal for budget minded and bootstrapped startups. In this session you will learn how to manage a production ready AWS account capable of scaling as your startup grows for less than $100/month before credits. We will discuss AWS Budgets, Cost Explorer, architect priorities, and the importance of having flexible, optimized Infrastructure as Code. We will wrap everything up discussing opportunities where to save with AWS services such as S3, EC2, Load Balancers, Lambda Functions, RDS, and many others.
Jeremy Millul - A Talented Software DeveloperJeremy Millul
Jeremy Millul is a talented software developer based in NYC, known for leading impactful projects such as a Community Engagement Platform and a Hiking Trail Finder. Using React, MongoDB, and geolocation tools, Jeremy delivers intuitive applications that foster engagement and usability. A graduate of NYU’s Computer Science program, he brings creativity and technical expertise to every project, ensuring seamless user experiences and meaningful results in software development.
Jira Administration Training – Day 1 : IntroductionRavi Teja
This presentation covers the basics of Jira for beginners. Learn how Jira works, its key features, project types, issue types, and user roles. Perfect for anyone new to Jira or preparing for Jira Admin roles.
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowSMACT Works
In today's fast-paced business landscape, financial planning and performance management demand powerful tools that deliver accurate insights. Oracle EPM (Enterprise Performance Management) stands as a leading solution for organizations seeking to transform their financial processes. This comprehensive guide explores what Oracle EPM is, its key benefits, and how partnering with the right Oracle EPM consulting team can maximize your investment.
Presentation given at the LangChain community meetup London
https://lu.ma/9d5fntgj
Coveres
Agentic AI: Beyond the Buzz
Introduction to AI Agent and Agentic AI
Agent Use case and stats
Introduction to LangGraph
Build agent with LangGraph Studio V2
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMAnchore
Over 70% of any given software application consumes open source software (most likely not even from the original source) and only 15% of organizations feel confident in their risk management practices.
With the newly announced Anchore SBOM feature, teams can start safely consuming OSS while mitigating security and compliance risks. Learn how to import SBOMs in industry-standard formats (SPDX, CycloneDX, Syft), validate their integrity, and proactively address vulnerabilities within your software ecosystem.
AI Creative Generates You Passive Income Like Never BeforeSivaRajan47
For years, building passive income meant traditional routes—stocks, real estate, or
online businesses that required endless hours of setup and maintenance. But now,
Artificial Intelligence (AI) is redefining the landscape. We’re no longer talking about
automation in the background; we’re entering a world where AI creatives actively
design, produce, and monetize content and products, opening the floodgates for
passive income like never before.
Imagine AI tools writing books, designing logos, building apps, editing videos, creating
music, and even selling your digital products 24/7—without you lifting a finger after
setup. This isn't the future. It’s happening right now. And if you act fast, you can ride
the wave before it becomes saturated.
In this in-depth guide, we’ll show you how to tap into AI creativity for real, sustainable,
passive income streams—no fluff, no generic tips—just actionable, traffic-driving
insights.
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfAlkin Tezuysal
As the demand for vector databases and Generative AI continues to rise, integrating vector storage and search capabilities into traditional databases has become increasingly important. This session introduces the *MyVector Plugin*, a project that brings native vector storage and similarity search to MySQL. Unlike PostgreSQL, which offers interfaces for adding new data types and index methods, MySQL lacks such extensibility. However, by utilizing MySQL's server component plugin and UDF, the *MyVector Plugin* successfully adds a fully functional vector search feature within the existing MySQL + InnoDB infrastructure, eliminating the need for a separate vector database. The session explains the technical aspects of integrating vector support into MySQL, the challenges posed by its architecture, and real-world use cases that showcase the advantages of combining vector search with MySQL's robust features. Attendees will leave with practical insights on how to add vector search capabilities to their MySQL systems.
Data Virtualization: Bringing the Power of FME to Any ApplicationSafe Software
Imagine building web applications or dashboards on top of all your systems. With FME’s new Data Virtualization feature, you can deliver the full CRUD (create, read, update, and delete) capabilities on top of all your data that exploit the full power of FME’s all data, any AI capabilities. Data Virtualization enables you to build OpenAPI compliant API endpoints using FME Form’s no-code development platform.
In this webinar, you’ll see how easy it is to turn complex data into real-time, usable REST API based services. We’ll walk through a real example of building a map-based app using FME’s Data Virtualization, and show you how to get started in your own environment – no dev team required.
What you’ll take away:
-How to build live applications and dashboards with federated data
-Ways to control what’s exposed: filter, transform, and secure responses
-How to scale access with caching, asynchronous web call support, with API endpoint level security.
-Where this fits in your stack: from web apps, to AI, to automation
Whether you’re building internal tools, public portals, or powering automation – this webinar is your starting point to real-time data delivery.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2025/06/state-space-models-vs-transformers-for-ultra-low-power-edge-ai-a-presentation-from-brainchip/
Tony Lewis, Chief Technology Officer at BrainChip, presents the “State-space Models vs. Transformers for Ultra-low-power Edge AI” tutorial at the May 2025 Embedded Vision Summit.
At the embedded edge, choices of language model architectures have profound implications on the ability to meet demanding performance, latency and energy efficiency requirements. In this presentation, Lewis contrasts state-space models (SSMs) with transformers for use in this constrained regime. While transformers rely on a read-write key-value cache, SSMs can be constructed as read-only architectures, enabling the use of novel memory types and reducing power consumption. Furthermore, SSMs require significantly fewer multiply-accumulate units—drastically reducing compute energy and chip area.
New techniques enable distillation-based migration from transformer models such as Llama to SSMs without major performance loss. In latency-sensitive applications, techniques such as precomputing input sequences allow SSMs to achieve sub-100 ms time-to-first-token, enabling real-time interactivity. Lewis presents a detailed side-by-side comparison of these architectures, outlining their trade-offs and opportunities at the extreme edge.
Create Your First AI Agent with UiPath Agent BuilderDianaGray10
Join us for an exciting virtual event where you'll learn how to create your first AI Agent using UiPath Agent Builder. This session will cover everything you need to know about what an agent is and how easy it is to create one using the powerful AI-driven UiPath platform. You'll also discover the steps to successfully publish your AI agent. This is a wonderful opportunity for beginners and enthusiasts to gain hands-on insights and kickstart their journey in AI-powered automation.
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashBluebash
Understand the differences between MCP vs A2A vs ACP agent communication protocols and how they impact AI agent interactions. Get expert insights to choose the right protocol for your system. To learn more, click here: https://www.bluebash.co/blog/mcp-vs-a2a-vs-acp-agent-communication-protocols/
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashBluebash
Ad
lecture 5 string in c++ explaination and example.ppt
1. CS 103 1
Strings in C++
The string Class
• Definition of Strings
• How to declare strings in C++: the string class
• Operations on strings
– Concatenation, comparison operators, and [ ]
• Functions of the string class
– length, size, empty,
– insert, substr, replace, erase, clear, find
• Useful char functions in the C library <ctype.h>
2. CS 103 2
Definition of Strings
• Generally speaking, a string is a sequence
of characters
• Examples: “hello”, “high school”, “H2O”.
• Typical desirable operations on strings are:
– Concatenation: “high”+“school”=“highschool”
– Comparisons: “high”<“school” // alphabetical
– Finding/retrieving/modifying/deleting/inserting
substrings in a given string
3. CS 103 3
Strings in C
• In C, a string can be a specially terminated char array or char
pointer
– a char array, such as char str[ ]=“high”;
– a char pointer, such as char *p = “high”;
• If a char array, the last element of the array must be equal to
‘0’, signaling the end
• For example, the above str[] is really of length 5:
str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘0’
• The same array could’ve been declared as:
– char str[5] = {‘h’,’i’, ‘g’,’h’,’0’};
• If you write char str[4] = {‘h’,’i’, ‘g’,’h’};, then str is an
array of chars but not a string.
• In char *p=“high”; the system allocates memory of 5
characters long, stores “high” in the first 4, and ‘0’ in the
5th
.
4. CS 103 4
The string Class in C++
• C++ has a <string> library
• Include it in your programs when you wish
to use strings: #include <string>
• In this library, a class string is defined and
implemented
• It is very convenient and makes string
processing easier than in C
5. CS 103 5
Declaration of strings
• The following instructions are all equivalent. They
declare x to be an object of type string, and assign
the string “high school” to it:
– string x(“high school”);
– string x= “high school”;
– string x; x=“high school”;
6. CS 103 6
Operations on strings
(Concatenation)
• Let x and y be two strings
• To concatenate x and y, write: x+y
string x= “high”;
string y= “school”;
string z;
z=x+y;
cout<<“z=“<<z<<endl;
z =z+“ was fun”;
cout<<“z=“<<z<<endl;
Output:
z=highschool
z= highschool was fun
7. CS 103 7
Concatenation of Mixed-Style
Strings
• In where s is of type string,
– u can be
A string object, or
a C-style string (a char array or a char pointer),
a C-style char
or a double-quoted string,
or a single-quoted character.
– Same with v and w.
– At least u or v or w must be a string object
s=u+v+w;
8. CS 103 8
Example of Mixed-Style
Concat
string x= “high”;
char y[]= “school”;
char z[]= {‘w’,’a’,’s’,’0’};
char *p = “good”;
string s= x+y+’ ‘+z+” very”+” “+p+’!’;
cout<<“s=“<<s<<endl;
cout<<“s=“+s<<endl;
Output:
s=highschool was very good!
s=highschool was very good!
9. CS 103 9
The concat-assign Operator +=
• Assume x is a string object.
• The statement
x += y;
is equivalent to
x=x+y;
where y can be a string object, a C-style
string variable, a char variable, a double-
quoted string, or a single-quoted char.
10. CS 103 10
Comparison Operators for
string Objects
• We can compare two strings x and y using the
following operators: ==, !=, <, <=, >, >=
• The comparison is alphabetical
• The outcome of each comparison is: true or false
• The comparison works as long as at least x or y is
a string object. The other string can be a string
object, a C-style string variable, or a double-
quoted string.
11. CS 103 11
Example of String Comparisons
string x= “high”;
char y[]= “school”;
char *p = “good”;
If (x<y)
cout<<“x<y”<<endl;
If (x<“tree”)
cout<<“x<tree”<,endl;
If (“low” != x)
cout<<“low != x”<<endl;
if( (p>x)
cout<<“p>x”<<endl;
Else
cout<<“p<=x”<<endl;
Output:
x<y
x<tree
low != x
p>x
12. CS 103 12
The Index Operator []
• If x is a string object, and you wish to
obtain the value of the k-th character in the
string, you write: x[k];
• This feature makes string objects appear
like arrays of chars.
string x= “high”;
char c=x[0]; // c is ‘h’
c=x[1]; // c is ‘i’
c=x[2]; // c is g
13. CS 103 13
Getting a string Object Length
& Checking for Emptiness
• To obtain the length of a string object x,
call the method length() or size():
• To check of x is empty (that is, has no
characters in it):
int len=x.length( );
--or--
int len=x.size( );
bool x.empty();
14. CS 103 14
Obtaining Substrings of Strings
• Logically, a substring of a string x is a subsequence
of consecutive characters in x
• For example, “rod” is a substring of “product”
• If x is a string object, and we want the substring
that begins at position pos and has len characters
(where pos and len are of type int), write:
• The default value of len is x.length( )
• The default value for pos is 0
string y = x.substr(pos,len);
string y = x.substr(pos);//x[pos..end-1]
15. CS 103 15
Inserting a String Inside Another
• Suppose x is a string object, and let y be
another string to be inserted at position pos
of the string of x
• To insert y, do:
• The argument y can be: a string object, a
C-style string variable, or a double-quoted
string
x.insert(pos,y);
16. CS 103 16
Replacing a Substring by
Another
• Suppose x is a string object, and suppose
you want to replace the characters in the
range [pos,pos+len) in x by a string y.
• To do so, write:
• The argument y can be: a string object, a
C-style string variable, or a double-quoted
string
x.replace(pos,len,y);
17. CS 103 17
Deleting (Erasing) a Substring
of a string Object
• Suppose x is a string object, and suppose
you want to delete/erase the characters in the
range [pos,pos+len) in x.
• To do so, write:
• The default value of len is the x.length( )
• The default value for pos is 0
• To erase the whole string of x, do:
x.erase(pos,len);
x.clear( );
x.erase(pos); // erases x[pos..end-1]
18. CS 103 18
Searching for (and Finding)
Patterns in Strings
• Suppose x is a string object, and suppose
you want to search for a string y in x.
• To do so, write:
• This method returns the starting index of
the leftmost occurrence of y in x, if any
occurrence exits; otherwise, the method
returns the length of x.
• To search starting from a position pos, do
int startLoc = x.find(y);
int startLoc = x.find(y, pos);
19. CS 103 19
Searching for Patterns (Contd.)
• To search for the rightmost occurrence of y
in x, do
• In all the versions of find and rfind, the
argument y can be a string object, a C-style
string variable, double-quoted string, a char
variable, or a single-quoted char.
startLoc = x.rfind(y); // or
startLoc = x.rfind(y, pos);
20. CS 103 20
An Example
string x=“FROM:[email protected]”;
int colonPos=x.find(‘:’);
string prefix=x.substr(0,colonPos); //=FROM
string suffix = x. substr(colonPos+1);
cout<<“-This message is from ”<<suffix<<endl;
Output:
-This message is from [email protected]
21. CS 103 21
Another Example
#include <fstream>
// this code segment reads lines from an input file and
// appends them to a string object called body. It does
// so until it sees a line equal to ##########
ifstream in(“inputFileName.txt”);
string body; char line[1000];
while(in.getline(line,1000)){ //puts in line the next line w/o n
string lineString (line);
if (lineString != "##########")
body += lineString +'n';// appends line to body
else
break; // exits the while loop
}
22. CS 103 22
Trimming Leading & Trailing Spaces
// this function removes leading and trailing spaces from x
void trim (string& x){
int k = 0; // k will procced to the first non-blank char
while(k<x.size() &&(x[k]==' ' || x[k]=='t' || x[k]=='n'))
k++;
x. erase(0,k);
int s=x.size();
// s will move backward to the rightmost non-blank char
while(s>0 &&(x[s-1]==' ' || x[s-1]=='t' || x[s-1]=='n'))
s--;
x.erase(s);
}
23. CS 103 23
What if You Want to Use C-Style
Strings
• You can!
• C has a library <strings.h> which provides several
string processing functions
• Some of the more commonly used functions in
that library are presented in the next two slides
• In those functions, most of the arguments are of
type char *str. That can be replaced by char str[];
24. CS 103 24
C Library <strings.h> for String
Operations
• char *strcpy(char *dst, char *src);
– Copies the string src to string dest
• char *strncpy(char *dst, char *src, int n);
– Copies the first n characters of src to dest
• char * strcat(*dst, char *src);
– Concatenate src to the end of dst.
• char * strcat(*dst, char *src, int n);
– Concatenate first n chars of src to end of dst.
25. CS 103 25
• int strcmp(char *str1, char *str2);
– Returns 0 if str1=str2, negative if str1<str2, positive if str1>str2
• int strncmp(char *str1, char *str2, int n);
– Same as strcmp except it considers the first n chars of each string
• int strlen(char *str); // returns the length of str
• char * strchr(char *str, int c);
– Returns a char pointer to the 1st
occurrence of character c in str, or
NULL otherwise.
• char * strstr(char *str, char *pat);
– Returns a char pointer to the 1st
occurrence of string pat in str, or
NULL otherwise.
• Plus some other commands
• Remarks:
– in strcpy, strncpy, strcat, and strncat, make sure that the dst string has
enough space to accommodate the string copied or cancatenated to it
– If the strings are arrays, also make sure that the array dst is large enough
to to accommodate the string copied or cancatenated to it
26. CS 103 26
Correspondence between the C
library and the C++ string Class
C Library Functions C++ string operators/methods
strcpy = (the assignment operator)
strcat += (assign+concat operator)
strcmp = =, !=, <, >, <=, >=
strchr, strstr
strrchr
.find( ) method
.rfind( ) method
strlen .size( ) or .length( ) methods
27. CS 103 27
Char Functions in C (and C++)
• The <ctype.h> library in C provides useful
functions for single char variables
• The next slide gives the most common char
functions.
• Although the input argument appears to be
of type int, it is actually a char.
28. CS 103 28
• int isalnum(int c); //non-zero iff c is alphanumeric
• int isalpha(int c); //non-zero iff c is alphabetic
• int isdigit(int c); //non-zero iff c a digit: 0 to 9
• int islower(int c); //non-zero iff c is lower case
• int ispunct(int c); //non-zero iff c is punctuation
• int isspace(int c); //non-zero iff c is a space char
• int isupper(int c); // non-zero iff c is upper case
• int isxdigit(int c); //non-zero iff c is hexadecimal
• int tolower(int c); //returns c in lower case
• int toupper(int c); //returns c in upper case
29. CS 103 29
An example of Using char Functions
//PRECONDITION: str a string object
//POSTCONDITION: every lower-case alphabetical letter
//in str is replaced by its upper-case counterpart
void toupper(string& str){
for(int i=0;i<str.size();i++){
char c=str[i];
if (islower(c)){
char C = toupper(c);
string strC; strC=C;
str.replace(i,1,strC);
}
}
}