Categories
kinsta.com

What’s the Average PHP Developer Salary? Deep Dive into Data for 2020

PHP development: some consider it a popular language with a promising future, others an outdated technology that’s not worth the time to learn. But what do the numbers say, especially when you take a look at PHP developer salary?

While there are certainly many newer, flashier, and more exciting languages out there, PHP remains a reliable staple of backend web development and a skill many employers are still searching for.

Interested in becoming a PHP developer yourself? We’ve covered the average web developer’s salary already, now let’s dive into PHP and see how its income compares.

Quick note: We’re rounding numbers here, so make sure to check the original sources for more exact values.

Is PHP Developer a Good Job?

So you’re considering becoming a PHP developer. But is that really the job for you? Besides the issue of salary, is it a good career that’s worth pursuing?

There are a few things to keep in mind about PHP. Like any other programming language, it has its positives and negatives. If this is a career you’re set on, you’ll find that there are plenty of reasons to try it.

First: PHP is a very easy language to learn. Other programming languages can be confusing before you get used to them, using obscure naming conventions or high-level coding standards that are difficult to memorize.

But PHP is clear, readable, and easy to understand. If you have any programming background or even a vague understanding of how web development works, you can get a general idea of what a PHP string is doing just by looking at it. It’s one of the best languages to start with.

This simplicity does mean more competition, though. So starting out, you may have a lower salary. But highly proficient PHP developers are sought after, so if you can master it, you have the potential to earn lots of money. That popularity means there are plenty of career opportunities out there.

Another good reason to learn PHP: it pairs great with other skills and languages. You could learn HTML/CSS and JavaScript to be a full stack developer or get into database management with SQL. C/C++ programs can also interact with PHP. And with PHP’s exec() function, it can work with pretty much anything else.

Unlike newer languages, PHP isn’t a gamble. It’s tried and tested, with major projects like WordPress keeping it relevant even in 2020. Your job isn’t going anywhere any time soon, and that’s why so many developers continue to work with it.

What Does a PHP Developer Do?

As a PHP developer, what will your general daily tasks be? For that, we’ll need to answer what PHP is and how you can use it.

PHP is a general-purpose scripting language. What this means is that it executes scripts in real-time (unlike “compiled programming languages†which run all at once at launch), and can be used to create any kind of application — though it’s far more often used for web development.

It’s also a server-side language, which means its code is executed on your server rather than in the visitors’ browsers, unlike a client-side language such as JavaScript or CSS. This makes it more secure and suitable for tasks like sending data to your server that can’t be easily manipulated.

That’s generally what PHP is used for: dynamic tasks that require changing files on your web server or in the database. While JavaScript and other client-side languages can dynamically affect how your website looks and acts without bogging down your server with requests, PHP works in the background to execute key tasks.

As a PHP developer, you’ll be tasked with the backend development of websites, laying the groundwork for web-based applications and behind-the-scenes jobs. You may make secure forms and other user input areas, work alongside the frontend developers, and hook databases to your PHP apps.

And of course, you’ll need to come up with inventive ways to solve problems and implement the features your clients want using PHP.

After the initial setup period, you’ll need to continue doing maintenance. That means fixing incompatibilities when they arise, updating your code when new versions of PHP release, and maintaining databases and forms.

What Do You Need to Be a PHP Developer?

Entering any development field requires a similar set of skills, though backend development and PHP do come with their own unique requirements.

First up: Education. These days, employers for technical jobs care more about experience than a degree, especially for junior positions and with easy-to-learn languages like PHP. Freelancing, internships, and entry-level jobs could be a very good way to build yourself up and get the experience necessary to land a good job.

Being a good developer does require a range of core skills, however:

Additionally, knowing how to work with databases is practically a must. And even if you’re not a full stack developer, you should understand the basics of HTML/JavaScript and how they interact with PHP so you can identify compatibility errors.

The Average PHP Developer’s Salary

Now comes the moment you’ve all been waiting for: the salary numbers.

Keep in mind that these statistics are entirely self-reported; only developers who sign up to these websites and put in their salaries contribute to the estimate. So the numbers won’t be perfectly accurate, but they can give you a general idea of what you should expect your income to be.

If you’d like a more official source, the Bureau of Labor in the US reported that web developers made $74k per year in 2019. This is all web developers, not just PHP developers, but it gives you something to compare your projected salary to.

You can also check out our report on web developer salaries to see how PHP development holds up.

Now let’s get into the average salary for PHP developers.

  • Glassdoor: $81k/year, with a low of $55k and a high of $100k.
  • ZipRecruiter: $86k/year, with a low of $16k and a high of $137k.
  • PayScale: $64k/year, with a low of $43k and a high of $94k.
  • Indeed: $94k/year, based on job offers posted on the site.
PHP developer salary

PHP developer salary (avg.)

Overall, not bad! Averaging all these you get an estimate of $81k/year. That’s pretty good for a language as easy to learn as PHP; a few hours a day of study could turn you from an unskilled worker into a talented developer with a comfortable salary.

Do keep in mind that for computer science and programming fields, this is actually a fairly low salary. Other languages can pay much better, at over $100k/year, especially in the United States.

PHP Developer Salaries By Experience Level

Salary for developers widely varies vastly by experience. More experience means you can handle more unassisted and help out younger developers, so companies are willing to pay extra.

First up: Junior, or entry-level, salaries. There’s not a big difference between the two other than the title. This is what you can expect to earn from your first job as a PHP developer, with little to no experience and perhaps some education under your belt.

As a junior PHP developer, you’ll have no more than two or three years of experience, and will be tasked with writing basic code and doing most of the bug fixing.

The average PHP developer salary for junior candidates looks like this:

  • Glassdoor: $64k/year, with a low of $45k and a high of $90k.
  • ZipRecruiter: $62k/year, with a low of $26k and a high of $92k.
  • Salary.com: $63k/year, with a typical salary range of $56k-$71k.

As you can see the numbers don’t vary much, so this is probably a fairly accurate estimate.

Next up is senior-level PHP developer salaries. As a senior, you should have 3-5 years of experience, possibly ten or more.

Senior PHP developer salary

Senior PHP developer salary (avg.)

You’ll be expected to work without supervision, write quality code, and potentially oversee and train others. With all that responsibility comes a higher salary. And here is where getting into PHP really pays off.

  • Glassdoor: $92k/year, with a low of $68k and a high of $128k.
  • ZipRecruiter: $101k/year, with a low of $44k and a high of $137k.
  • PayScale: $88k/year, with a low of $61k and a high of $121k.

Agency vs. Freelancing PHP Developer Salary

Freelancing is hard. You’re 100% responsible for earning your own pay and doing all your marketing to boot. You need to get found before you can earn any money, and it’s very difficult to get off the ground. But just how much lower is it?

It might not be as bad as you’d expect. In fact, freelance PHP developers have the potential to make quite a bit of money.

According to ZipRecruiter, freelance PHP developers make an average of $89k/year, or $43/hour. Compared to the general freelance web developer salary of $75k (or about $36/hour) reported by Glassdoor, this is quite a bit better.

CodeMentor reports that freelance PHP developers make on average $61-80/hour. With a standard 40-hour workweek (keep in mind you will likely work less, especially at first), that’s $127k-$166k/year.

Freelance PHP developer salary

Freelance PHP developer’s hourly rate (avg.)

And how does this compare to agency salaries? Most freelancers wouldn’t describe themselves as “junior†or “senior†PHP developers, so it would be a good idea to look back at those salaries for an accurate comparison.

Averaging the data from all sources:

  • Junior PHP developers make $63k/year
  • Senior PHP developers make about $94k/year

Freelance PHP developers, on the other hand, have the potential to earn quite a bit more. It all depends on the hourly rate you set, and how well you can pitch that rate to clients.

Need a blazing-fast, secure, and developer-friendly hosting for your client sites? Kinsta is built with WordPress developers in mind and provides plenty of tools and a powerful dashboard. Check out our plans

Average PHP Developer’s Salary By Country

Many of these salary reports can be a bit biased towards developers in the United States.

If you’re living outside the US, what can you expect to earn as a PHP developer? Here are PHP developer salaries in Europe; the rest of the data was collected from Glassdoor. Note that these have all been converted to USD for this list.

  • Switzerland: $83k/year.
  • USA: $81k/year.
  • Australia: $73k/year.
  • Denmark: $73k/year.
  • Norway: $70k/year.
  • Sweden: $58k/year.
  • Germany: $56k/year.
  • UK: $52k/year.
  • The Netherlands: $52k/year.
  • Finland: $50k/year.
  • France: $45k/year.
  • Canada: $47k/year.
  • Spain: $34k/year.
  • Portugal: $22k/year.
  • India: $8k/year.
international PHP developer salaries

DDI Development

Check out job listings in your area to get a more accurate idea of what you can expect!

 

In short: the US is definitely one fo the highest-paying country, due likely both to demand as well as the high cost of living compared to some other countries. You might also want to check out this list of the average PHP developer salary by state in the US. New York is the top ranker with $94k/year, and North Carolina the lowest at only $69k/year.

Full Stack PHP Developer Salary

Full stack developers have a wide range of skills. You’ll use PHP for the backend, while also maintaining the frontend with HTML, CSS, and JavaScript. In addition to that, you’ll likely be working with database code as well.

That’s basically an entire website all in one, so you’d expect to be earning a pretty good salary.

  • Glassdoor: $106k/year.
  • ZipRecruiter: $85k/year, with a low of $27k and a high of $137k.
  • Indeed: $113k/year, based on over 17k salaries.
Full stack PHP developer salary

Full stack PHP developer salary (avg.)

This is among the highest of all the PHP developer salaries, even compared against senior devs. Enough experience can really pay off!

Are PHP Developers Paid Less?

Now that you’ve seen the data, how do these salaries compare to other development languages? While seniors, full stack, and successful freelancers make decent money, for the average PHP developer, data related to their salary expectations doesn’t look that exciting:

programming language salaries

Programming language salaries

Whether you use our numbers collected from Glassdoor, Payscale, and similar sites, or other surveys, PHP is consistently near the very bottom. The only language that seems to ever pay less is HTML and CSS.

Why is that?

The ease of learning the language could be part of it. PHP is a great starter skill that’s easy to pick up, but that of course means you’re competing with tons of junior developers for clients and company positions.

You can learn PHP in two weeks to a month of studying and practice. You don’t need much technical expertise to break into it: you can go from zero programming skills to writing functional PHP apps in just a few weeks.

On the other hand, the creator of one of the current top-ranking salaried languages, Scala, has a course on Coursera. It takes approximately seven months to complete! This isn’t just something you can jump into as your first programming language, either. You need past experience.

But as you grow and move past low-skilled competition, learning how to code more complex tasks in PHP and handle larger projects, you’ll find that your salary becomes much more comparable to other languages.

Summary

PHP is known for having a lower salary compared to other programming languages, and the numbers do indicate that. Besides HTML and CSS, PHP is one of the lowest-reported developer salaries. There are definitely more well-paying software jobs out there.

Despite this, it still offers decent money and good opportunities to advance in your career. Just think about the WordPress ecosystem, which is filled with themes and plugins to work on and companies that always about to launch a new product.

Senior and full stack PHP developers, who have years of experience and skills in a variety of languages, are the ones who earn the most. Starting out, expect a lower salary, but know that as you grow it will only be better.

 

Categories
linuxhint.com

10 Types of Security Vulnerabilities

An unintended or accidental flaw in the software code or any system that makes it potentially exploitable in terms of access to illegitimate users, malicious behaviours like viruses, trojans, worms, or any other malware is called a security vulnerability. The use of software that has already been exploited or the use of weak and default passwords also results in making the system vulnerable to the outside world. These types of security vulnerabilities require patching to prevent hackers from using previously used exploits on them again to gain unauthorized access to the system. A security vulnerability also called security hole or weakness is a flaw, a bug, or a fault in the implementation of code, design, and architecture of a web application and servers, which when left unaddressed can result in compromising of the system and makes the whole network vulnerable to the attack. The people going to be infected include the application owner, application users, and any other person relying on that application. Let’s look at the most dangerous and common security risks to web applications.

Table of Contents

  1. Database Injection
  2. Broken Authentication
  3. Sensitive Data Exposure
  4. XML External Entities (XEE)
  5. Broken Access Control
  6. Security Misconfiguration
  7. Cross-site Scripting (XSS)
  8. Insecure Deserialization
  9. Using Components with Known Vulnerabilities
  10. Insufficient Logging and Monitoring

Database Injection:

In case of sending untrusted pieces of data to the interpreter as a part of command through any area that takes user input i.e form input or any other data submission area, injection flaws occur. The attacker’s malicious queries can trick the interpreter into executing commands that can show up confidential data that the user has no authorization to have a look at. For example in an SQL injection attack, when the form input is not properly sanitized,  the attacker can enter the SQL database and access its contents without authorization, just by entering malicious SQL database code in a form that is expecting a plaintext. Any type of field that takes the user’s input is injectable i.e parameters, environment variables, all web services, etc.

The application is vulnerable to the injection attack when user-supplied data is not sanitized and validated, by the use of dynamic queries without context-aware escaping and the use of hostile data directly. Injection flaws can easily be discovered through the examination of code and by the use of automated tools like scanners and fuzzers. To prevent injection attacks, there is some measure that can be taken like separating the data from commands and queries, use of a safe API that provides a parameterized interface, use of “white-list†server-side input validation through tools like Snort, escaping of special characters using specific escape syntax, etc.

An injection attack can lead to a massive data loss, disclosure of confidential information, denial of access and it can even lead to a complete application takeover. Some SQL controls like LIMIT can be used to control huge amounts of data loss in case of an attack. Some types of injection attacks are SQL, OS, NoSQL, LDAP injection attacks.

Broken authentication:

Attackers can access user accounts and can even compromise the whole host system through admin accounts, using the vulnerabilities in authentication systems. Authentication flaws allow the attacker to compromise passwords, session tokens, authentication keys and can be chained with other attacks that can lead to unauthorized access of any other user account or session temporarily and in some cases, permanently. Let’s say a user has a wordlist or a dictionary of millions of valid user names and passwords obtained during a breach. He can use them one by one in an extremely less time using automated tools and scripts on the login system to see if anyone does work. Poor implementation of identity management and access controls leads to vulnerabilities like broken authentication.

The application is vulnerable to authentication attack when it permits trying of different usernames and passwords, permits dictionary attacks or brute force attacks without any defense strategy, use easy, default passwords or passwords that are leaked in any breach, exposes session ids in URL, uses poor password recovering scheme, uses a pattern of cookies. Broken authentication can be exploited easily using simple tools for brute-forcing and dictionary attacks with a good dictionary. These types of attacks can be prevented using multi-factor authentication systems, by implementing weak password checks by running a password through a bad passwords’ database, by not using default credentials, by aligning password complexity policy, by the use of good server-side session manager which generates a new random session-id after login, etc.

Broken authentication vulnerability can result in compromising a few user accounts and an admin account, that is all an attacker needs to compromise a system. These types of attacks lead to identity theft, social security fraud, money laundering, and disclosure of highly classified information. The attacks include dictionary attacks, brute-forcing, session hijacking, and session management attacks.

Sensitive data exposure:

Sometimes web applications do not protect sensitive data and info like passwords, database credentials, etc. An attacker can easily steal or modify these weakly protected credentials and use it for illegitimate purposes. Sensitive data should be encrypted while at rest or in transit and have an extra layer of security otherwise attackers can steal it. Attackers can get their hands on sensitive exposed data and steal hashed or clear text users & database credentials off the server or a web browser. For example, if a password database uses unsalted or simple hashes to store passwords, a file upload flaw can allow an attacker to retrieve the passwords database which will lead to exposure of all passwords with a rainbow table of pre-calculated hashes.

The main flaw is not only that the data is not encrypted, even if it is encrypted, but weak key generation, weak hashing algorithms, weak cipher usage can also result in these types of one of the most common attacks. To prevent these types of attacks, first, classify which kind of data can be considered as sensitive according to the privacy laws and apply controls as per classification. Try not to store any classified data you don’t need, wash it as soon as you use it. For the data in transit, encrypt it with secure protocols i.e TLS with PFS ciphers, etc.

These types of vulnerabilities can result in the exposure of highly sensitive information like credit card credentials, health records, passwords, and any other personal data that can lead to identity theft and bank fraud, etc.

XML External Entities (XEE):

Poorly configured XML processors process external entity references inside XML documents. These external entities can be used to retrieve internal files’ data like /etc/passwd file or to perform other malicious tasks.  Vulnerable XML processors can easily be exploited if an attacker can upload an XML document or include XML etc. These vulnerable XML entities can be discovered using SAST and DAST tools or manually by inspecting dependencies and configurations.

A web application is vulnerable to the XEE attack due to many reasons like if the application accepts direct XML input from untrusted sources, Document Type Definitions(DTDs) on the application are enabled, the application uses SAML for identity processing as SAML uses XML for identity insertions, etc. XEE attacks can be mitigated by avoiding serialization of sensitive data, using less complicated data formats i.e JSON, patching XML processors the application is curren’]tly using and even the libraries, disabling DTDs in all XML parsers, validation of XML file upload functionality using XSD verification, etc.

The application vulnerable to these types of attacks can lead to DOS attack, Billion Laughs’ attack, scanning of internal systems, internal port scanning,  executing a remote command which results in affecting all application data.

Broken Access Control:

Access Control is giving users privileges to do specific tasks. Broken access control vulnerability takes place when the users are not properly restricted on the tasks they can perform. Attackers can exploit this vulnerability that can end up in accessing unauthorized functionality or information. Let’s say a web application allows the user to change the account he is logged in from just by changing the URL to another user’s account without further verification.  Exploiting the access control vulnerability is a go-to attack of any attacker, this vulnerability can be found manually as well as by using SAFT and DAFT tools. These vulnerabilities exist due to a lack of testing and automated detection of web applications although the best way to find them is to do it manually.

Vulnerabilities contain privileges escalation i.e acting as a user you are not or acting as an admin while you are a user, bypassing access control checks just by modifying the URL or changing the application’s state, metadata manipulation, allowing the primary key to be changed as another user’s primary key, etc. To prevent these kinds of attacks, access control mechanisms must be implemented in server-side code where attackers can’t modify the access controls. Enforcement of unique application business limits by domain models, disabling of listing server directories, alert admin on repeated failed login attempts, invalidation of JWT tokens after the logout must be ensured to mitigate these kinds of attacks.

Attackers can act as another user or administrator using this vulnerability to perform malicious tasks like creating, deleting and modifying records, etc. Massive data loss can occur if the data is not secured even after a breach.

Security misconfiguration:

The most common vulnerability is security misconfiguration. The main reason for the vulnerability is the use of default configuration, incomplete configuration, Adhoc configurations, poorly configured HTTP headers, and verbose error messages containing more info than the user actually should have known. At any level of a web application, security misconfigurations can occur i.e database, web server, application server, network services, etc. Attackers can exploit unpatched systems or access unprotected files and directories to have an unauthorized hold on the system. For example, an application excessively verbose error messages that help the attacker to know vulnerabilities in the application system and the way it works. Automated tools and scanners can be used to detect these types of security flaws.

A web application contains this type vulnerability if it is missing the security hardening measures across any part of the application, unnecessary ports are open or it enables unnecessary features, default passwords are used, error handling reveals over informative errors to the attacker, it is using unpatched or outdated security software, etc. It can be prevented by removing unnecessary features of the code, i.e a minimal platform without unnecessary features, documentation, etc, enabling a task to update and patch the security holes as part of patch management processes, the use of a process to verify the effectiveness of security measures taken, the use of repeatable hardening process to make it easy to deploy another environment that is properly locked down.

These types of vulnerabilities or flaws allow the attacker to gain unauthorized access to system data which leads to the complete compromisation of the system.

Cross-Site Scripting (XSS):

XSS vulnerabilities happen at the point when a web application incorporates untrusted data in a new website page without legitimate approval or escaping, or refreshes a current site page with client-provided data, utilizing a browser API that can make HTML or JavaScript.  XSS flaws occur in case the website allows a user to add custom code into a URL path which can be seen by other users. These flaws are used to run malicious JavaScript code on the target’s browser. Let’s say, an attacker can send a link to the victim containing a link to any company’s website. This connection could have some malicious JavaScript code embedded in it, In case that the bank’s webpage isn’t appropriately secured against XSS attacks, on clicking on the link the malicious code will be run on the victim’s browser.

Cross-Site Scripting is a security vulnerability that is present in almost ⅔ of the web applications. An application is vulnerable to XSS if the application stores an unsanitized user input that can be seen by another user, by the use of JavaScript structures, single-page applications, and APIs that powerfully incorporate attacker controllable information to a page are helpless against DOM XSS. XSS attacks can be mitigated by the use of frameworks that escapes and sanitize XSS input by nature like React JS etc, learning the limitations of frameworks and cover them using one’s own cases, escaping unnecessary and untrusted HTML data everywhere i.e in HTML attributes, URI, Javascript, etc, use of context-sensitive encoding in case of modifying document on client-side, etc.

XSS based attacks are of three types i.e Reflected XSS, DOM XSS, and Stored XSS. All types of these attacks have a significant amount of impact but in the case of Stored XSS, the impact is even larger i.e stealing of credentials, sending malware to the victim, etc.

Insecure deserialization:

The serialization of data means taking objects and converting them to any format so that this data can be used for other purposes later on, while deserialization of data means the opposite of that. Deserialization is unpacking this serialized data for the use of applications. Insecure deserialization means tempering of data that has been serialized just before that is about to be unpacked or deserialized.  Insecure deserialization leads to the remote code execution and it is used to perform other tasks for malicious purposes like privileges escalation, injection attacks, replay attacks, etc. There are some tools available for discovering these kinds of flaws but human assistance is needed frequently to validate the problem. Exploiting deserialization is a bit difficult as the exploits won’t work without some manual changes.

When the application deserializes malicious objects supplied by the attacking entity. This can lead to two types of attacks i.e attacks related to data structure and objects in which the attacker modifies application logic or execute remote code and typical data tampering attacks in which existing data structures are used with modified content for example access control related attacks.  Serialization can be used in remote process communication (RPC) or an inter-process communication (IPC), caching of data, web services, databases cache server, file systems, API authentication tokens, HTML cookies, HTML form parameters, etc. Deserialization attacks can be mitigated by not using serialized objects from untrusted sources, implementing integrity checks, isolating the code running in a low privileged environment, monitoring incoming and outgoing network connections from servers that deserialize frequently.

Using components with known vulnerabilities:

Different components like libraries, frameworks, and software modules are used by most of the developers in the web application. These libraries help the developer to avoid unnecessary work and provide the functionality needed. Attackers look for flaws and vulnerabilities in these components to coordinate an attack. In case of finding a security loophole in a component can make all the sites using the same component, vulnerable. Exploits of these vulnerabilities are already available while writing a custom exploit from scratch takes a lot of effort. This is a very common and widespread issue, the use of large amounts of components in developing a web application can lead to not even knowing and understanding all components used, patching and updating all the components is a long go.

An application is vulnerable if the developer doesn’t know the version of a component used, the software is outdated i.e the operating system, DBMS, software running, runtime environments and the libraries, the vulnerability scanning is not done regularly, the compatibility of patched software are not tested by the developers. It can be prevented by removing unused dependencies, files, documentation, and libraries, checking the version of the client and server-side components regularly, obtaining components and libraries from official and trusted secure sources,  monitoring the unpatched libraries and components, ensuring a plan for updating and patching vulnerable components regularly.

These vulnerabilities lead to minor impacts but can also lead to compromisation of the server and the system. Many large breaches relied on known vulnerabilities of components. The use of vulnerable components undermine application defences and can be a starting point for a large attack.

Insufficient logging and monitoring:

Most systems don’t take enough measures and steps to detect data breaches. The average response time of an incident is 200 days after it has happened, this is a lot of time to do all the nasty stuff for an attacking entity. Insufficient logging and monitoring allow the attacker to further attack the system, maintain its hold on the system, tamper, hold and extract data as per the need. Attackers use the lack of monitoring and response in their favour to attack the web application.
Insufficient logging and monitoring occur at any time i.e logs of applications not being monitored for unusual activities, auditable events like failed login attempts and high transaction values are not properly logged, warnings and errors generate unclear error messages, no trigger alert in case of pentesting using automated DAST tools,  being unable to detect or alert active attacks quickly, etc. These can be mitigated by ensuring all the login, access control failures,  and server-side input validation can be logged to identify malicious user account and held for enough amount of time for delayed forensic investigation, by ensuring that the logs generated are in a format compatible with centralized log management solutions, by ensuring integrity checks at high-value transactions, by establishing a system for timely alerts of suspicious activities, etc.

Most of the successful attacks start with checking and probing for vulnerabilities in a system, allowing these vulnerability probing can result in compromising the whole system.

Conclusion:

The security vulnerabilities in a web application affect all the entities related to that application. These vulnerabilities must be taken care of to provide a safe and secure environment for the users. Attackers can use these vulnerabilities to compromise a system, get hold of it, and escalate privileges. The impact of a compromised web application can be visualized from stolen credit card credentials and identity theft to the leaking of highly confidential information etc. depending on the needs and attack vectors of malicious entities.

Categories
linuxhint.com

How to use C++ String Class

A string literal is a sequence of characters in a constant array pointer terminated by the nul character, . When identified, by a variable, the string literal cannot really reduce or increase in length. Many operations cannot be done on the string literal. So, there is a need for a string class. The C++ string class is for a data structure, a collection of characters in sequence, which allows member functions and operators to act on the characters. The string class allows more manipulations on the corresponding string literal, than just the string literal. You need to have good knowledge of string literal, to understand this article.

Class and Objects

A class is a set of variables and functions that work together; where the variables do not have values assigned to. When values are assigned to the variables, the class becomes an object. Different values given to the same class result in different objects; that is, different objects are the same class with different values. Creating an object from a class is said to be instantiating the object.

The name, string, is a class. An object created from the string class has a programmer chosen name.

A function that belongs to the class is needed to instantiate an object from the class. In C++, that function has the same name as the name of the class. Objects created (instantiated) from the class have different names given to them, by the programmer.

Creating an object from a class means constructing the object; it also means instantiating.

A C++ program which uses the string class, starts with the following lines at the top of the file:

#include <iostream>
#include <string>
using namespace std;

The first line is for input/output. The second line is to allow the program to use all the features of the string class. The third line allows the program to use the names in the standard namespace.

Overloading a Function

When two or more different function signatures have the same name, that name is said to be overloaded. When one function is called, the number and type of arguments, determine which function is executed.

Construction

string()
The following statement constructs a string of zero length with no character.

string strCol = string();

It begins with the name of the class (object type), string. This is followed by the name for the object string, given by the programmer. The assignment operator follows; then the name of the constructor with empty parentheses. Here, strCol is the instantiated object with all the data members (properties) and member functions (methods).
string(str)
This is similar to the above, but takes either a string literal or an identifier as an argument, in the constructor. The following statement illustrates this:

string strCol = string(“I love you”);

Construction with Initializer List

The following code illustrates this:

string strCol = string({‘I’,‘ ‘,‘l’,‘o’,‘v’,‘e’,‘ ‘,‘y’,‘o’,‘u’,});

The string literal is “I love you”. Note the nul character at the end of the initializer list.

string(str, n)

This forms a string collection, of the first n characters of another string. The following code illustrates this:

char str[] = “I love you”;
string strCol = string(str, 6);
cout << strCol << n;

The output is “I love†with the first 6 characters from “I love youâ€. Remember: the single space is a character.

string(str, pos, n)

This forms a string collection of n characters, beginning from the zero-based indexed position, pos, of another string. The following code illustrates this:

char str[] = “I love you”;
string strCol = string(str, 2, 4);
cout << strCol << n;

The output is, “loveâ€.

For the above two cases, if n is greater than the size of the string, the out_of_range exception is thrown – see later.

string(n, ‘c’)

Forms a collection of n characters, where all the characters are the same. Consider,

string strCol = string(5,‘e’);
cout << strCol << n;

The output is, “eeeeeâ€, 5 e’s.

Assigning a String

A string can be assigned as follows, after having declared both strings:

string strCol1 = string(“I love you”);
string strCol2;
strCol2 = strCol1;
cout << strCol2 << n;

The output is, “I love you”.

Constructing with Iterator

An iterator provides a generic representation of scanning, through the values of a collection. A syntax to create a string with iterator, is:

template<class InputIterator>
basic_string(InputIterator begin, InputIterator end, const Allocator&
 a = Allocator());

This constructs a string for the range [begin, end) – see details later.

Destroying a String

To destroy a string, just let it go out of scope.

String Class Element Access

An instantiated string object can be sub-scripted (indexed) like an array. Index counting begins from zero.

stringName[i]

The operation “stringName[i]†returns a reference to the character (element) at the ith index of the character collection. The following code outputs v:

string strCol = string(“I love you”);
char ch = strCol[4];
cout << ch << n;

stringName[i] const

The operation “stringName[i] const†is executed instead of “stringName[i]†when the string object is a constant object. It is used in the following code for example:

const string strCol = string(“I love you”);
char ch = strCol[4];
cout << ch << n;

The expression returns a constant reference to the ith element of the string object. None of the elements of the string can be changed.

Assigning a Character with Subscript

A character can be assigned to a non-constant string object, as follows:

string strCol = string(“I call”);
strCol[2] = ‘f’;
cout << strCol << n;

The output is “I fallâ€. ‘c’ was changed to ‘f’.

stringName.at(i)

“stringName.at(i)†is similar to “stringName[i]â€, but “stringName.at(i)†is more reliable. The following code shows how it should be used:

string strCol = string(“I love you”);
char ch = strCol.at(4);
cout << ch << n;

at() is actually a string class member function.

stringName.at(i) const

“stringName.at(i) const†is similar to “stringName[i] constâ€, but “stringName.at(i) const†is more reliable. “stringName.at(i) const†is executed instead of “stringName.at(i)†when the string object is a constant string object. It is used in the following code, for example:

const string strCol = string(“I love you”);
char ch = strCol.at(4);
cout << ch << n;

“at() const†is actually a string class member function.

Assigning a Value with the at() Function

A value can be assigned to a non-constant string object, with the at() function, as follows:

string strCol = string(“I call”);
strCol.at(2) = ‘f’;
cout << strCol << n;

The output is “I fallâ€.

Problem with Sub-scripting

The problem with sub-scripting (indexing) is, that if the index is out of range, the wrong result may be obtained, or an error may be issued at run-time.

front()

This returns a reference to the first element of the string object, without removing the element. The output of the following code is ‘I’.

string strCol = string(“I love you”);
char ch = strCol.front();
cout << ch << n;

The character is not removed from the string object.

front() const

When the string object construction is preceded by const, the expression “front() const†is executed instead of “front()â€. It is used in the following code, for example.

const string strCol = string(“I love you”);
char ch = strCol.front();
cout << ch << n;

A constant reference is returned. The element is not removed from the string object. No character can be changed for a constant string object.

back()

This returns a reference to the last element of the string object, without removing the element. The output of the following code is ‘u’.

string strCol = string(“I love you”);
char ch = strCol.back();
cout << ch << n;

back() const

When the string object construction is preceded by const, the expression “back() const†is executed instead of “back()â€. It is used in the following code, for example.

const string strCol = string(“I love you”);
char ch = strCol.back();
cout << ch << n;

A constant reference is returned. The element is not removed from the string object.

String Capacity

size_type capacity() const noexcept

The total number of characters the string can hold without requiring reallocation, is returned by this capacity member function. A code segment for this is:

string strCol = string();
int num = strCol.capacity();
cout << num << n;

The output is 15 on my computer.

reserve(n)

Memory space is not always available in free store. Extra space can be reserved in advance. Consider the following code segment:

string strCol = string(“love”);
strCol.reserve(6);
cout << strCol.capacity() << n;

The output is 15 on my computer.

size() const noexcept

This returns the number of characters in the string. The following code illustrates:

string strCol = string(“I love you”);
int num = strCol.size();
cout << num << n;

The output is 10, which does not include the nul, character.

length() const noexcept

same as size().
Note: size() <= capacity() .

shrink_to_fit()

Can reduce capacity() to size() by causing reallocation; it is not obligatory. The following code demonstrates this:

string strCol = string(“I love you”);
strCol.reserve(12);
strCol.shrink_to_fit();
int sz = strCol.size();
cout << sz << n;

The output is 10 and not 12 or 16. The function returns void.

resize(sz), resize(sz,’c’)

This resizes the string. If the new size is smaller than the old size, then the elements towards the end are erased. If the new size is longer, then some default character is added towards the end. To have a particular character added, use the resize() function with two arguments. The following code segment illustrates the use of the two functions:

string strCol = string(“I love you”);
strCol.resize(6);
cout << “New size of strCol: “ << strCol.size() << n;
string strCol1 = string(“I love”, ‘e’);
strCol1.resize(12);
cout << “New size of strCol1: “ << strCol1.size() << n;

The output is:

New size of strCol: 6
New size of strCol1: 12
The function returns void.

clear() noexcept

Removes all elements from the string, as the following code segment illustrates:

string strCol = string(“I love you”);
strCol.clear();
cout << strCol.size() << n;

The output is 0. The function returns void.

empty() const noexcept

This returns 1 for true if there is no character in the string object, or 0 for false if the string object is not empty. The following code illustrates this:

string strCol1 = string(“I love you”);
cout << strCol1.empty() << n;
string strCol2 = string();
cout << strCol2.empty() << n;

The output is:

0
1

Returning Iterators and the String Class

An iterator is like a pointer but has more functionality than the pointer.

begin() noexcept

Returns an iterator that points to the first character (element) of the string object, as in the following code segment:

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.begin();
cout << *iter << n;

The output is ‘I’. Note the way the declaration that receives the iterator, has been declared. The iterator is dereferenced in a return expression to obtain the value, in the same way, that a pointer is dereferenced.

begin() const noexcept;

Returns an iterator that points to the first element of the string object collection. When the object construction is preceded by const, the expression “begin() const†is executed instead of “begin()â€. Under this condition, the corresponding element in the object cannot be modified. It is used in the following code, for example.

const string strCol = string(“I love you”);
basic_string<char>::const_iterator iter = strCol.begin();
cout << *iter << n;

The output is ‘I’. Note that const_iterator has been used this time, instead of just iterator, to receive the returned iterator.

end() noexcept

Returns an iterator that points immediately beyond the last element of the string object. Consider the following code segment:

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.end();
cout << *iter << n;

The output is null, which is nothing, as there is no concrete element beyond the last element.

end() const noexcept

Returns an iterator that points immediately beyond the last element of the string object. When the string object construction is preceded by const, the expression “end() const†is executed instead of “end()â€. Consider the following code segment:

const string strCol = string(“I love you”);
basic_string<char>::const_iterator iter = strCol.end();
cout << *iter << n;

The output is null. Note that const_iterator has been used this time, instead of just iterator, to receive the returned iterator.

Reverse Iteration

It is possible to have an iterator that iterates from the actual end to just before the first element:

rbegin() noexcept

Returns an iterator that points to the last element of the string instantiated object, as in the following code segment:

string strCol = string(“I love you”);
basic_string<char>::reverse_iterator iter = strCol.rbegin();
cout << *iter << n;

The output is ‘u’. Note the way the declaration that receives the reverse iterator, has been declared. The iterator is dereferenced in a return expression to obtain the value, in the same way, that a pointer is dereferenced.

rbegin() const noexcept;

Returns an iterator that points to the last element of the string object. When the object construction is preceded by const, the expression “rbegin() const†is executed instead of “rbegin()â€. Under this condition, the corresponding element in the object cannot be modified. The feature is used in the following code, for example.

const string strCol = string(“I love you”);
basic_string<char>::const_reverse_iterator iter = strCol.rbegin();
cout << *iter << n;

The output is ‘u’. Note that const_reverse_iterator has been used this time, instead of just reverse_iterator, to receive the returned iterator.

rend() noexcept

Returns an iterator that points just before the first element of the string object. Consider the following code segment:

string strCol = string(“I love you”);
basic_string<char>::reverse_iterator iter = strCol.rend();
cout << *iter << n;

The output is null, which is nothing, as there is no concrete element just before the first element.

rend() const noexcept

Returns an iterator that points just before the first element of the string object. When the object construction is preceded by const, the expression “rend() const†is executed instead of “rend()â€. Consider the following code segment:

const string strCol = string(“I love you”);
basic_string<char>::const_reverse_iterator iter = strCol.rend();
cout << *iter << n;

The output is null. Note that const_reverse_iterator has been used this time, instead of just reverse_iterator, to receive the returned iterator.

String Modifiers

A modifier that modifies the string object, can also take or return an iterator.

Appending

basic_string& operator+=(const basic_string& str)

Appends the right string object to the left string object. Example:

string strCol1 = string(“I love”);
string strCol2 = string(” you”);
strCol1 += strCol2;
cout << strCol1 << n;

The output is “I love youâ€. Do not forget that “strCol1 += strCol2†is same as “strCol1 = strCol1+strCol2â€.

basic_string& operator+=(const charT* s)

Appends a string literal to a string object collection. Example:

string strCol = string(“I love”);
strCol += ” you”;
cout << strCol << n;

Output: “I love youâ€.

basic_string& operator+=(charT c)

Appends a single character to an object string. Example:

string strCol = string(“I love yo”);
strCol += ‘u’;
cout << strCol << n;

Output: “I love youâ€.

basic_string& operator+=(initializer_list<charT>)

Appends an initializer list. Example:

string strCol = string(“I love”);
strCol += {‘ ‘,‘y’,‘o’,‘u’,};
cout << strCol << n;

Output: “I love youâ€. It is always good to add the nul, at the end of a character initializer list.

basic_string& append(const basic_string& str)

Appends the argument string object to the main string object. Example:

string strCol1 = string(“I love”);
string strCol2 = string(” you”);
strCol1.append(strCol2);
cout << strCol1 << n;

Output: “I love youâ€.

basic_string& append(const charT* s)

Appends a string literal argument to the main string. Example

string strCol = string(“I love”);
strCol = strCol.append(” you”);
cout << strCol << n;

Output: “I love youâ€.

basic_string& append(initializer_list<charT>)

Appends the initializer list, which is an argument, to the main string. Example:

string strCol = string(“I love”);
strCol = strCol.append({‘ ‘,‘y’,‘o’,‘u’,});
cout << strCol << n;

Output: “I love youâ€. It is always good to add the nul, character at the end of an initializer list.

basic_string& append(size_type n, charT c)

Appends n of the same character. Example:

string strCol = string(“tab”);
strCol = strCol.append(2, ‘o’);
cout << strCol << n;

Output: “tabooâ€.

basic_string& append(const charT* s, size_type n)

Appends the first n elements of a string literal to the main string object. Example:

string strCol = string(“I love”);
strCol = strCol.append(” you so”, 4);
cout << strCol << n;

The output is: “I love youâ€. If n is greater than the length of the literal, a length_error exception is thrown.

basic_string& append(const basic_string& str, size_type pos, size_type n = npos)

Appends n characters from the index, pos to the main string. Example:

string strCol = string(“I love”);
strCol = strCol.append(“ve you so”, 2, 4);
cout << strCol << n;

Output: “I love youâ€. An exception would also be thrown here, see later.

Assigning

basic_string& assign(const basic_string& str)

Assigns the argument string object to the main string, replacing any content that was there.

string strCol1 = string(“I love you”);
string strCol2 = string(“She needs me”);
strCol1 = strCol1.assign(strCol2);
cout << strCol1 << n;

Output: “She needs meâ€.

basic_string& assign(const charT* s)

Assigns a string literal argument to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”);
cout << strCol << n;

Output: “She needs meâ€.

basic_string& assign(initializer_list<charT>)

Assigns an initializer list argument to the main string, replacing any content that was there.
[cc lang=“c” escaped=“true” width=“780”]
string strCol = string(“I love you”);
strCol = strCol.assign({‘S’,‘h’,‘e’,‘ ‘,‘n’,‘e’,‘e’,‘d’,‘s’,‘ ‘,‘m’,‘e’,});
cout << strCol << n;

Output: “She needs meâ€. It is good to always add the nul, at the end of the character list, to form a string literal.

basic_string& assign(const charT* s, size_type n)

Assigns the first n characters of a string literal argument to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”, 9);
cout << strCol << n;

Output: “She needsâ€.

basic_string& assign(size_type n, charT c)

Assigns an argument of n of the same characters to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(4, ‘e’);
cout << strCol << n;

Output: eeee

basic_string& assign(const basic_string& str, size_type pos,
size_type n = npos)

Assigns n characters of a string object argument, beginning from pos, to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”, 4, 5);
cout << strCol << n;

Output: “needsâ€. Would throw an exception – see later.

Inserting

basic_string& insert(size_type pos, const basic_string& str)

Inserts the string object argument to the main string, at index, pos.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate and “);
strCol1 = strCol1.insert(2, strCol2);
cout << strCol1 << n;

Output: “I hate and love youâ€. Would throw an exception – see later.

basic_string& insert(size_type pos1, const basic_string&
 str,size_type pos2, size_type n = npos)

Inserts a length of n characters from pos2 of string object argument, to the main string, at index, pos1.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate, want and need”);
strCol1 = strCol1.insert(2, strCol2, 6, 9);
cout << strCol1 << n;

Output: “I want and love youâ€.

iterator insert(const_iterator p, charT c)

Inserts a particular character, which is an argument, into the position pointed to by the iterator. Returns an iterator for the position of the newly inserted character.

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter; ++iter; ++iter; ++iter; ++iter;
basic_string<char>::iterator retI = strCol.insert(iter, ‘d’);
cout << *retI << n;
cout << strCol << n;

The output is:

‘d’

“I loved youâ€

iterator insert(const_iterator p, size_type n, charT c)

Inserts n of the same character of the argument, into the position, pointed to by the iterator. Returns an iterator for the position of the beginning of the newly inserted same characters.

string strCol = string(“Tab in the land.”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter; ++iter;
basic_string<char>::iterator retI = strCol.insert(iter, 2, ‘o’);
cout << *retI << n;
cout << strCol << n;

The output is:

‘o’

“Taboo in the land.”

 

basic_string& insert(size_type pos, const charT* s)

Inserts an argument string literal at the index, pos in the main string.

string strCol = string(“Tab in the land.”);
strCol = strCol.insert(3, “oo”);
cout << strCol << n;

Output: “Taboo in the land.”

basic_string& insert(size_type pos, const charT* s, size_type n)

Inserts the first n characters of the argument string literal, at the index, pos in the main string.

string strCol = string(“Tab in the land.”);
strCol = strCol.insert(3, “oooo”, 2);
cout << strCol << n;

Output: “Taboo in the land.”

Replacing

basic_string& replace(size_type pos1, size_type n1, const basic_string& str))

Replaces n1 characters in the main string object from index, pos1, with the argument string object.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate you and”);
strCol1 = strCol1.replace(2, 4, strCol2);
cout << strCol1 << n;

Output: “I hate you and youâ€. Would throw an exception – see later.

basic_string& replace(size_type pos1, size_type n1, const basic_string&
 str,size_type pos2, size_type n2 = npos)

Replaces n1 characters in the main string object from the index, pos1, with n2 characters of the argument string object from the index, pos2.

string strCol1 = string(“I love you”);
string strCol2 = string(“we hate him and her”);
strCol1 = strCol1.replace(2, 4, strCol2, 3, 12);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos1, size_type n1, const charT* s,
 size_type n2)

Replaces n1 characters in the main string object from the index, pos1, with the first n2 characters of the literal string argument.

string strCol1 = string(“I love you”);
strCol1 = strCol1.replace(2, 4, “hate him and her”, 12);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos, size_type n, const charT* s)

Replaces n characters in the main string object from index, pos, with the literal string argument.

string strCol1 = string(“I love you”);
strCol1 = strCol1.replace(2, 4, “hate him and”);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos1, size_type n1, size_type n2, charT c)

Replaces n1 characters in the main string object from the index, pos1, with n2 of the same character of the argument.

string strCol1 = string(“A bad tablet there.”);
strCol1 = strCol1.replace(9, 3, 2, ‘o’);
cout << strCol1 << n;

Output: “A bad taboo there.â€.

iterator erase(const_iterator p)

Removes a character at the position pointed to by the iterator; then returns the iterator position, which is now occupied by the character that was next to this character (or end()). The following code illustrates this:

string strCol = string(“abcd”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter;
strCol.erase(iter);
cout << strCol[0] << ‘ ‘ << strCol[1] <<
<< strCol[2]<< n;

The output: a b d

basic_string& erase(size_type pos = 0, size_type n = npos)

Removes n characters from the index, pos.

string strCol = string(“abcd”);
strCol.erase(1, 2);
cout << strCol[0] << ‘ ‘ << strCol[1] << n;

Output: a d

void push_back(charT c)

To add a single character at the end of the string:

string strCol = string(“abcd”);
strCol.push_back(‘5’);
cout << strCol << n;

Output: abcd5

void pop_back()

Removes the last character without returning it. The size of the string is reduced by 1.

string strCol = string(“abcde”);
strCol.pop_back();
cout << strCol << n;

Output : abcd

void swap(basic_string& s)

The literals of two string objects can be swapped.

string strCol1 = string(<a id=“post-69618-__DdeLink__781_3724385525”></a>“abcde”);
string strCol2 = string(“1234567”);
strCol1.swap(strCol2);
cout << strCol1 << n;
cout << strCol2 << n;

The output is:

“1234567”
“abcde”

String Operations

const charT* c_str() const noexcept

Returns a pointer to the first element of the string. The pointer can be incremented.

const string strCol = string(“abcde”);
const char* p = strCol.c_str();
cout << *p << n;
++p;
cout << *p << n;

Output is:

a
b

Because of the second const in the heading, the program cannot change any character in the string. The construction is preceded by const.

const charT* data() const noexcept

Returns a pointer to the first element of the string. The pointer can be incremented.

const string strCol = string(“abcde”);
const char* p = strCol.data();
cout << *p << n;
++p;
cout << *p << n;

Output is:

a
b

Because of the second const in the heading, the program cannot change any character in the string. The construction is preceded by const.

basic_string substr(size_type pos = 0, size_type n = npos) const

Returns a string object of n characters for the sub-string beginning from the index, pos.

const string strCol = string(“abcdefghij”);
const string retStr = strCol.substr(2, 4);
cout << retStr << n;

Output: cdef

find() Member Functions

size_type find(const basic_string& str, size_type pos = 0) const noexcept

Looks for a sub-string object beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“We are the world!”);
string strCol1 = string(“the”);
int num = strCol.find(strCol1, 2);
cout << num << n;

Output:

index: 7
Returns -1, when not found.

size_type find(const charT* s, size_type pos = 0) const

Looks for a sub-string literal beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“We are the world!”);
int num = strCol.find(“are”, 0);
cout << num << n;

Since “pos = 0†is the default, 0 in the argument could have been omitted.

Output: 3

Returns -1, when not found.

size_type find (const charT* s, size_type pos, size_type n) const

Looks for the first n characters of a sub-string literal beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“The biggest boy”);
int num = strCol.find(“bigger”, 1, 3);
cout << num << n;

Output: 4

Returns -1, when not found.

size_type find(charT c, size_type pos = 0) const

Looks for the character, c beginning from the index, pos. If found, returns the beginning of the sub-string in the main string. If not found, returns -1.

string strCol = string(“We are the world!”);
int num = strCol.find(‘z’);
cout << num << n;

Output: -1

The following reverse find() member functions exist:

size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;
size_type rfind(const charT* s, size_type pos = npos) const;
size_type rfind(const charT* s, size_type pos, size_type n) const;
size_type rfind(charT c, size_type pos = npos) const;

Comparison Member Functions

int compare(const basic_string& str) const noexcept

Compares the argument string object with the main string object. If the main string occurs before the argument (in the dictionary) it returns a positive number. If it occurs after the main string, it returns a negative number. If the two strings are the same, it returns zero.

string strCol1 = string(“crowd”);
string strCol2 = string(“people”);
int num = strCol1.compare(strCol2);
cout << num << n;

Output: -13

int compare(const charT* s) const

Same as above, but the argument is a string literal.

string strCol1 = string(“people”);
int num = strCol1.compare(“people”);
cout << num << n;

Output: 0

String Operators

These operators are applicable to string objects and not necessarily string literals.

+

Concatenates two string objects, and returns the concatenation.

string strCol1 = string(“dancing on”);
string strCol2 = string(” the moon”);
string strCol = strCol1+strCol2;
cout << strCol << n;

Output: “dancing on the moonâ€.

==

Returns 1 for true, if the string objects are the same; and zero for false, if they are not.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 == strCol2;
cout << bl << n;

Output: 0

!=

Returns 1 if the string objects are not the same, and zero if they are.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 != strCol2;
cout << bl << n;

Output: 1

<

Returns 1, if the left operand is less than the right operand according to the dictionary, or zero if it is not.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 < strCol2;
cout << bl << n;

Output: 0

For ordinary characters in C++, in ascending order, numbers come before uppercase letters, which come before lowercase letters. The space character comes before zero and all of them.

C++ Main String Character Types

char

The char type is the original C++ type and would typically store a character in 8 bits.

char16_t

This stores a character in 16 bits.

char32_t

This stores a character in 32 bits.

wchar_t

char16_t and char32_t are wide characters. wchar_t is a wide-character that is proprietary and implementation-defined.

These types are called traits. However, C++ refers to them technically as, specializations of traits. This article has focused on the char type. The approach to the other types is slightly different – see later.

Other String Operation Member Functions

The signatures of other string operation functions are:

size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_of(const charT* s, size_type pos = 0) const;
size_type find_first_of(charT c, size_type pos = 0) const;
size_type find_last_of (const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_of (const charT* s, size_type pos, size_type n) const;
size_type find_last_of (const charT* s, size_type pos = npos) const;
size_type find_last_of (charT c, size_type pos = npos) const;
size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_not_of(const charT* s, size_type pos = 0) const;
size_type find_first_not_of(charT c, size_type pos = 0) const;
size_type find_last_not_of (const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_not_of (const charT* s, size_type pos, size_type n) const;
size_type find_last_not_of (const charT* s, size_type pos = npos) const;
size_type find_last_not_of (charT c, size_type pos = npos) const;

Conclusion

C++ has string literals and string objects. The string object has a collection of characters in sequence, similar to an array of characters in sequence. The difference between the string collection and an array, is, that the string collection can grow in length or shrink in length. A string object is instantiated (constructed) from a string class. A string object is a data structure with member functions. The member functions can be classified under the headings of object construction, element access, string capacity, string member functions with iterator arguments and return types, and string modifiers. String equality and relational operators also exist.