- Using Concat on C++ Strings
- Concatenation in C++
- The + Operator
- Appending to C++ Strings
- Using the strcat() function
- Why Should We Concatenate?
- How to Reverse Concatenation
- Become a C++ Developer
- Объединить несколько строк в C++
- 1. Использование std::ostringstream
- 2. Использование string::append
- 3. Использование неявной конкатенации
- 4. Использование сравнения строк
- 5. Использование std::format
- String concatenation in cpp
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Using Concat on C++ Strings
Strings are a foundational tool in C++, just as in most programming languages. In fact, one of the first skills you’ll need to learn when picking up C++ is how to work with strings. In this article, we’ll explore how to join two or more C++ strings together through a process called concatenation.
Concatenation in C++
Before we look at specific methods for joining strings together, let’s get acquainted with “concatenation.” In programming languages, concatenating means generating a new object — usually a string — out of two or more original objects. It’s a key method to know when working with data objects, which themselves are C++ building blocks that every C++ developer must know.
So what does concatenation’s end result look like? Let’s look at an example. Say we have someone’s name and title:
string name = "Jane Doe"; string title = "Professor";
We want to merge the two strings using concatenation. The result will look something like this:
string properName = "Professor Jane Doe";
It’s as simple as that! Now that we have an understanding of what C++ string objects look like post-concatenation, let’s dive into how specifically we would achieve this result.
The + Operator
Employing the + operator is the most straightforward way to merge two or more strings into a single object. The + operator simply takes the C++ strings and adjoins them, returning a concatenated string object independent of the original two strings. Let’s take our previous example of Professor Jane Doe. In the examples that’ll follow, keep in mind that when we use string, we’ll be referring to the std::string class, an instantiation of the basic_string class template. For that reason, we include and std at the beginning of each program:
#include using namespace std; int main()
We get Professor Jane Doe written to the console. You’ll notice we included a space between the two variables — this is recommended over adding a space to the end or beginning of a string.The following approach to concat C++ strings with the + operator achieves the same result, but the added spaces within the input strings are inconsistent and messy:
string properName = "Professor " + "Jane" + " Doe";
It’s better to store your input strings in variables and add stand-alone spaces when necessary.
Using the + operator is great when you have more than two strings to concatenate or want a simple approach. Now let’s look at another in-built way to concat C++ strings.
Appending to C++ Strings
We can also use the in-built append() method to concat strings in C++. At face value, this method adds additional characters — the input to the append() method — to the string the method is called on. We can keep our program from the + operator and replace properName with the following line:
string properName = title.append(name);
The output to this is ProfessorJane Doe. Notice that here, we do not have a space between “Professor” and “Jane”. In order to get the proper spacing, we have options besides adding a space at the end of our title string. The advantage to using append() is that you have many options when it comes to parameters and manipulating your added string. We can simply chain the append() method to achieve our desired result:
string properName = title.append(1u,' ').append(name);
This outputs Professor Jane Doe as we’d expect! Now let’s look at a full program we can run with added arguments to append(). Here, we include substrings and parameter options outlined in the C++ documentation for this method:
#include using namespace std; int main () < string str; string name = "Professor Jane Doe"; string verb = "teaches"; string subjects1 = "math, programming"; string subjects2 = "writing and also debate."; str.append(name).append(" "); // "Professor Jane Doe " str.append(verb).append(" "); // "teaches " str.append(subjects1, 6).append(", "); // "programming, " str.append("biology as well", 7).append(", "); // "biology, " str.append(subjects1, 0, 4); // "math" str.append(3u,'.'); // ". " str.append(subjects2.begin()+8, subjects2.end()); // "and also debate." std::cout
Although you can start by appending to name and not use str at all, we began the output string with an empty string str to show that you don’t always need a value when you begin concatenating.
As you can see, you have a lot of options when using append(), so you might choose it over the + operator when you need to go more in-depth with string manipulation. Now, let’s look at a final way to concat strings with C++.
Using the strcat() function
This C-style method takes a destination string and appends a source string to it. This might sound just like the append() method, but there are a few key differences. First, the destination string must point to a character array already containing a C++ string. Second, that destination array must have enough space to contain the resulting concatenated string.
Let’s look at an example to understand how this method works:
Unlike the other methods, the strcat() function comes from the string.h library, so we include that instead of iostream and the std namespace. For the sake of simplicity, we also include white spaces at the end of each string. You might notice that before we start concatenating, we use strcpy() to copy the first source string (“Professor”) into the destination array str since it’s initially empty:
If your destination array is too small — for example, if we’d defined str as char str[5] — you’ll get an error that says exited, segmentation fault. If you don’t know how long your output will be, you can initialize the string right away so the compiler can calculate the length of the array for you:
char init[] = "This is the init string"; char add[] = " that I am adding to now."; strcat(init, add); puts(init); // writes "This is the init string that I am adding to now."
There are, however, potential performance issues with strcat() that have to do with time complexity and how many times a program runs the function. That’s beyond the scope of this article, but we encourage you to check out Joel Spolsky’s blog post on the topic.
Now that we know several methods for concatenating C++ strings, let’s move on to use cases for concatenation.
Why Should We Concatenate?
Use cases for concatenation abound, but let’s take a look at three of the most common scenarios in which you will want to concat C++ strings.
First, when we need to add a prefix to each of many words, we’ll want to use a C++ for loop to iterate over the words and concatenate the prefix to each string.
Above we saw a few examples of words being concatenated together to form a string. In real-world scenarios, we’ll often want to create a contiguous text out of three sentences, where each sentence is a string. To achieve this, we’ll simply need to use concatenation.
And third, you might come across a situation where you want to concatenate user input onto a prompt. Say you have a situation where a user needs to enter the birthdays of each of her family members. At the end of the program, we’d want to print the prompt for each individual along with the day entered, so we don’t get the birthdays mixed up. Here’s how that would work for one birthday:
#include using namespace std; int main() < string s1, s2, result; s1 = "My dog's birthday is: "; cout
We’ll now remember that the dog’s (and not the brother’s) birthday is July 12.
Now that we know how the concatenation of C++ strings can be useful, let’s touch on how to reverse C++ concatenation.
How to Reverse Concatenation
Let’s say we already have a concatenated string, and we actually want to split it up. How can we reverse concat strings? There are a few possible ways, with perhaps the most straightforward one involving strtok(), which lets you split up a string using a delimiter, or token.
Another approach is with the std library’s istringstream, which also lets you use supplied tokens to break a string into parts. Check out this Stack Overflow post to learn how to implement this method.
Become a C++ Developer
As a C++ developer you’ll often find yourself working with strings. While we only covered the basics of C++ string concatenation in this article, you can continue your learning journey by enrolling in our expert-taught C++ Nanodegree program.
Объединить несколько строк в C++
В этом посте мы обсудим, как объединить несколько строк в C++.
1. Использование std::ostringstream
2. Использование string::append
Чтобы добавить дополнительные строки в конец существующей строки, мы можем использовать функцию string::append функция-член. Его можно использовать следующим образом:
3. Использование неявной конкатенации
В C++ любые соседние строки объединяются компилятором в одну строку. Это известно как неявная конкатенация строк. Следующая программа на C++ демонстрирует это:
4. Использование сравнения строк
Другим распространенным подходом к объединению нескольких строковых объектов является использование оператора concat. (+) оператор. Вот как будет выглядеть код:
C++14 позволяет формировать строковый литерал различного типа, используя std::literals::string_literals::operator""s. Эти операторы объявлены в пространстве имен std::literals::string_literals . Например, следующий код объединяет строковые литералы со стандартным s-суффиксом.
5. Использование std::format
Начиная с C++20, мы можем использовать formatting library который предлагает безопасную и расширяемую альтернативу семейству функций printf. Чтобы объединить несколько строк, мы можем использовать std::format определено в заголовке , как показано ниже:
Это все, что касается объединения нескольких строк в C++.
Средний рейтинг 4.71 /5. Подсчет голосов: 14
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
String concatenation in cpp
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter