Как сложить строки в c
Конкатенация строк или объединение может производиться как с помощью операции + , так и с помощью метода Concat :
Метод Concat является статическим методом класса string, принимающим в качестве параметров две строки. Также имеются другие версии метода, принимающие другое количество параметров.
Для объединения строк также может использоваться метод Join :
Метод Join также является статическим. Использованная выше версия метода получает два параметра: строку-разделитель (в данном случае пробел) и массив строк, которые будут соединяться и разделяться разделителем.
Сравнение строк
Для сравнения строк применяется статический метод Compare :
Данная версия метода Compare принимает две строки и возвращает число. Если первая строка по алфавиту стоит выше второй, то возвращается число меньше нуля. В противном случае возвращается число больше нуля. И третий случай — если строки равны, то возвращается число 0.
В данном случае так как символ h по алфавиту стоит выше символа w, то и первая строка будет стоять выше.
Поиск в строке
С помощью метода IndexOf мы можем определить индекс первого вхождения отдельного символа или подстроки в строке:
Подобным образом действует метод LastIndexOf , только находит индекс последнего вхождения символа или подстроки в строку.
Еще одна группа методов позволяет узнать начинается или заканчивается ли строка на определенную подстроку. Для этого предназначены методы StartsWith и EndsWith . Например, в массиве строк хранится список файлов, и нам надо вывести все файлы с расширением exe:
Разделение строк
С помощью функции Split мы можем разделить строку на массив подстрок. В качестве параметра функция Split принимает массив символов или строк, которые и будут служить разделителями. Например, подсчитаем количество слов в сроке, разделив ее по пробельным символам:
Это не лучший способ разделения по пробелам, так как во входной строке у нас могло бы быть несколько подряд идущих пробелов и в итоговый массив также бы попадали пробелы, поэтому лучше использовать другую версию метода:
Второй параметр StringSplitOptions.RemoveEmptyEntries говорит, что надо удалить все пустые подстроки.
Обрезка строки
Для обрезки начальных или концевых символов используется функция Trim :
Функция Trim без параметров обрезает начальные и конечные пробелы и возвращает обрезанную строку. Чтобы явным образом указать, какие начальные и конечные символы следует обрезать, мы можем передать в функцию массив этих символов.
Эта функция имеет частичные аналоги: функция TrimStart обрезает начальные символы, а функция TrimEnd обрезает конечные символы.
Обрезать определенную часть строки позволяет функция Substring :
Функция Substring также возвращает обрезанную строку. В качестве параметра первая использованная версия применяет индекс, начиная с которого надо обрезать строку. Вторая версия применяет два параметра — индекс начала обрезки и длину вырезаемой части строки.
Вставка
Для вставки одной строки в другую применяется функция Insert :
Первым параметром в функции Insert является индекс, по которому надо вставлять подстроку, а второй параметр — собственно подстрока.
Удаление строк
Удалить часть строки помогает метод Remove :
Первая версия метода Remove принимает индекс в строке, начиная с которого надо удалить все символы. Вторая версия принимает еще один параметр — сколько символов надо удалить.
Замена
Чтобы заменить один символ или подстроку на другую, применяется метод Replace :
Во втором случае применения функции Replace строка из одного символа «о» заменяется на пустую строку, то есть фактически удаляется из текста. Подобным способом легко удалять какой-то определенный текст в строках.
Смена регистра
Для приведения строки к верхнему и нижнему регистру используются соответственно функции ToUpper() и ToLower() :
Объединить строки в C#
Конкатенация строк в C# выполняется с помощью + оператор. Мы можем использовать это для объединения двух или трех строк.
2. Использование String.Concat() метод
Простое и довольно эффективное решение для объединения двух или более строк с помощью String.Concat() метод.
3. Использование StringBuilder.Append() метод
StringBuilder.Append можно использовать для эффективного добавления нескольких строк. Это предпочтительное решение по сравнению с + оператор для объединения более трех строк.
4. Использование String.Join() метод
В следующем примере кода показано, как использовать String.Join() метод объединения нескольких строк с использованием пустой строки в качестве разделителя.
5. Использование String.Format() метод
Можно использовать String.Format() метод объединения нескольких строк друг с другом, как показано ниже:
6. Интерполяция строк
Начиная с C# 6, можно использовать Строковая интерполяция ($), который обеспечивает удобный синтаксис для преобразования целого числа в строку.
Это все, что касается объединения строк в C#.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 20
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
How do I concatenate two strings in C?
I tried name = «derp» + «herp»; , but I got an error:
Expression must have integral or enum type
![]()
12 Answers 12
C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.
Use strcat to concatenate two strings. You could use the following function to do it:
This is not the fastest way to do this, but you shouldn’t be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.
Call the function like this:
If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.
If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.
How to concatenate strings in C: A five minute guide
Modifying strings is an important programming skill. Concatenation involves appending one string to the end of another string.
For example, say we have two strings: “C programming” and “language”. We can use concatenation to generate the output, “C programming language.”
There are a few ways we can append or concatenate strings in C. This quick tutorial teaches you how to concentrate two strings using the strcat() function.
Today, we will go over:
Strings refresher in C
A string is one of the most popular data types in programming. It is a collection of characters grouped together. Under the hood, strings are actually arrays of characters. Just like arrays, we can access string elements through indexing.
The C language can be slightly awkward when it comes to dealing with strings, especially compared to languages like Python. In C, a string is denoted with the help of a character array. A string can be declared with the syntax below.
char stringName [stringSize] ;
Below, variable a is a character array where you can store up to 10 characters.
And it can be initialized as follows:
The C program automatically inserts the null character as shown to the right.
A null character is provided by the compiler, implicitly, in the style of initialization as seen to the right.
Let’s put these concepts together with two examples.
In C, strings are always null-terminated. This means that the last element of the character array is a “null” character, abbreviated \0 . When you declare a string as in line 8 above, the compiler does this for you.
Constant character strings are written inside double-quotation marks (see line 5 below), and single character variables are declared using single-quotation marks (see line 7 below).
We can use the sizeof() function to inspect our character string above to see how long it actually is:
Modifying Strings
In C, it is a bit tricky to modify a declared string. Once a string is declared to be a given length, you cannot just make it longer or shorter by reassigning a new constant to the variable.
There are many built-in functions for modifying strings. Consider two strings s1 and s2 . Here are few built-in functions that are available in the string.h header file:
- strlen(s1) : returns the length of a string.
- strcpy(s1, s2) : copies string s2 to s1
- strrev(s1) : reverses the given string
- strcmp(s1, s2) : returns 0 if s1 and s2 contain the same string.
- strcat(s1, s2) : concatenates two strings
How to append one string to the end of another
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
The basic process is as follows:
- Take the destination string
- Find the NULL character
- Copy the source string beginning with the NULL character of destination string
- Append a NULL character to the destination string once copied
Let’s look at an example. Below, the following code will concatenate two strings using the strcat() function:
In addition to modifying the original destination string, the strcat() function also returns a pointer to that string. This means that we can directly pass the strcat() function to the printf() function.
In C, the destination array must be initialized before passing it to strcat . This means that it must have at least 1 location with a NULL character.
strncat function for appending characters
The strncat function is slightly different. We can use this to append at most n characters from a source string to a destination string. The example below appends the first 5 characters from src at the end of dest (i.e. starting from the NULL character). It then appends a NULL character in the end.
Note: The destination array must be large enough to hold the following: the characters of the destination, n characters of the source, and a NULL character.
If the number of characters to copy exceeds the source string, strncat will stop appending when it encounters the NULL character, like below:
More C string questions
There is a lot more we can do with strings in C. Take a look at some of the common interview questions about strings to get a sense of what to learn:
- Edit all the contents of a string
- Replace every character of a string with a different character
- Map every character of one string to another so all occurrences are mapped to the same character
- Modify the string so that every character is replaced with the next character in the keyboard
- Make an array on strings using pointers
- Convert all the letters in a string to Uppercase letters
- Convert a string to an integer
- Splitting a string using strtok() in C
What to learn next
Congrats! You should now have a solid idea of how to concatenate two strings in C. It’s a simple process that is important to know for building your foundation. A good next step for your C journey is to learn some advanced C programming concepts like:
- Pointers and arrays
- I/O streams
- Debugging in C
- Advanced string modification
To help you with your journey, Educative offers a free course called Learn C From Scratch. This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language.
You’ll learn everything from data types, control flow, functions, input/output, memory, compilation, debugging, and other more.
Continue reading about C and strings
Join a community of 1.4 million readers. Enjoy a FREE, weekly newsletter rounding up Educative's most popular learning resources, coding tips, and career advice.