Как преобразовать string в string c

от admin

C++: String в string и нахождение позиции символа

Эта заметка продолжит цикл по преобразованию типов. В ней мы научимся преобразовывать System::String (String ^) в std::string (стандартную строку), а также находить символ в этой самой преобразованной строке.

В одной из своих программ (конкретно – написание калькулятора) я столкнулся с тем, что надо получить содержимое поля, а затем проверить, есть ли в нем запятая. Это требуется для того, что в числе может быть только одна запятая (точка) для разделения целой и дробной части числа. Да-да, задачу можно решить и по-другому, например, создать специальный флаг – нажата ли клавиша запятой – но мне захотелось вот так.

Итак, сама функция по приведению System::String к типу std::string выглядит вот так:

А теперь применим эту функцию на практике. Получим содержимое текстового поля и проверим, есть и в нем определенный символ, в данном случае – запятая:

Код на самом деле довольно прост и, как я думаю, в комментариях не нуждается. Единственно, что может быть непонятно — это переменная pos — в неё мы пишем номер позиции найденного символа. Если она равняется «-1», то такого символа, увы, в данной строке нет. На всякий случай напоминаю, что нумерация символов начинается с нуля.

Если же вам что-то все же непонятно, или требуется написать программу на C++, то вы можете обратиться ко мне. Пишите – и за некоторую сумму денег я вам помогу. Быстро, недорого и квалифицированно.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си плюс плюс

Пример 11. Преобразование string -строки в String -строку

Текст программы показан в листинге 14.12, а результат — на рис. 14.12.

Рис. 14.12. Результат преобразования string в String

// 14.12_2011 Прим 11.cpp : main project file.

#include «stdafx.h» #include <string> #include <iostream>

using namespace System; using namespace std;

string str = «test»;

//можно записать и так, используя конструктор:

//string str = string(«test»); cout << str << endl;

/*метод c_str() класса string преобразует string-строку

в обычную С-строку с символом ‘\0’ в качестве признака конца строки. string-строка такого признака конца не имеет, и этот символ может быть обычным ее символом. string-строка — это аналог AnsiString-строки

Часть II. Приложения Windows Form

String^ str2 = gcnew String(str.c_str()); Console::WriteLine(str2); Console::ReadLine();

Пример 12. Объявление дескрипторов в native-типах

Дескрипторами называют указатели в среде CLR. Именно они указывают на объект в управляемой куче. Напрямую нельзя объявить дескриптор в native-типе. Например, в native-функции вы не можете сделать объявление типа такого:

Компилятор вам выдаст ошибку. Файл vcclr.h содержит специальный настраиваемый шаблон gcroot , позволяющий ссылаться на CLR-объекты из С++ кучи, т. е. объекты из неуправляемой кучи могут ссылать на объекты из управляемой кучи. Тем самым устанавливается связь между различными средами. При этом вам позволяется использовать дескриптор в native-типы (например, в функции) и трактовать его как основной тип.

Шаблон gcroot создан на основе класса:

который обеспечивает дескрипторами объекты в управляемой куче.

Отметим, что сами дескрипторы автоматически удаляются деструктором класса gcroot только тогда, когда они больше не используются. Их нельзя удалять вручную. Если же вы создаете gcroot-объект в native-куче (т. е. в неуправляемой), то должны сами вызвать оператор delete для освобождения ресурса. В режиме исполнения программы поддерживается постоянная связь между дескриптором и CLRобъектом, на который он указывает. Если объект по тем или иным причинам перемещается в куче, дескриптор всегда возвращает новый адрес объекта. Переменная не может получить pin-указатель (предохраняющий объект от перемещения в такой куче), пока она назначена шаблону gcroot .

Текст программы показан в листинге 14.13, а результат — на рис. 14.13.

Рис. 14.13. Работа с дескриптором в native-памяти

Глава 14. Преобразование между нерегулируемыми и регулируемыми указателями

// 14.13_2011 Прим 12.cpp : main project file.

#include «stdafx.h» #include <vcclr.h>

using namespace System;

// compile with: /clr

public value struct V //CLR-структура

class Native //native-класс

/*член native-класса — дескриптор v_handle:*/ gcroot< V^ > v_handle;

int main() //managed-функция

Native native; //native-переменная, объявленная в managed-функции

V v; //managed-переменная

/*дескриптору присваивается значение v,

т. е. формируется ссылка на managed-структуру, из которой теперь можно извлекать ее элементы:*/ native.v_handle = v;

native.v_handle->str = «Hello to all»; Console::WriteLine(«String in V: <0>«, native.v_handle->str); Console::ReadLine();

Пример 13. Работа с дескриптором в native-функции

Текст программы показан в листинге 14.14, а результат — на рис. 14.14.

Рис. 14.14. Результат работы managed-типа в native-функции

Часть II. Приложения Windows Form

// 14.14_2011 Прим 13.cpp : main project file.

#include «stdafx.h» #include «gcroot.h» #include <conio.h>

using namespace System;

class StringWrapper //managed-класс

/*метод присваивает private-члену х класса

(т. е. дескриптору) адрес строки «ManagedString» в управляемой куче:*/

String ^ str = gcnew String(«ManagedString»); x = str;

/*метод-член класса присваивает переменной targetStr значение дескриптора х, который указывает

на строку «ManagedString», и выводит эту строку:*/ void PrintString()

Читать:
Даны два прямоугольника стороны которых параллельны или перпендикулярны осям координат

String ^ targetStr = x; Console::WriteLine(«StringWrapper::x == <0>«, targetStr);

How to Convert String Array to String in C#

How to Convert String Array to String in C#

In this article, we are going to learn how to convert a string array to a string in C#. We will cover five different approaches to achieve the same result, and in the end, we will inspect benchmark results to see the fastest way to accomplish the conversion.

Convert Using Loop and Addition Assignment Operator

The first and easiest way to convert a string array into a string is using the addition assignment += operator:

First, we create an empty string variable result to represent the final result. In the next step, we loop through the array and increment the result variable with each element inside the array. Then, we return the result variable containing every array’s element.

Even though it is an easy-to-implement approach, it is not a good one. Since the string is an immutable type, in each iteration, we copy the entire string content and add the new value to the result variable. It is also good to know that we can optimize some operations on single strings (like the Substring ) using Span.

That said, we are going to implement our second approach using a loop. Let’s do it.

Convert String Array to String Using Loop and StringBuilder

This approach is very similar to the previous one, with the exception that, this time, we are going to use the StringBuilder class instead of a string . Let’s create a UsingLoopStringBuilder method to accomplish this:

First, we instantiate a StringBuilder object to a result variable. Then, inside the loop, we append each element to it. In the end, we return the string inside the result variable using the result.ToString() .

Convert String Array to String Using String.Join

Let’s convert a string array into a string using a string.Join(. ) method:

The string class contains a static Join(. ) method, and with it, we can accomplish the same result.

The first input parameter of the string.Join(. ) method represents a separator used between each element. Since we don’t need any separator in our example, we use a string.Empty to represent an empty string. However, we could use any char, string, or even a white space to separate the elements. The second parameter represents the array of the elements we want to convert into a string.

Behind the scenes, the string.Join(. ) method also uses the StringBuilder class.

Convert Using String.Concat

Let’s create a UsingStringConcat method to convert a string array into a string:

First, our method receives the array we want to convert.

Then we call the string ‘s static Concat(. ) method. This method works similarly to the string.Join(. ) . Yet, it doesn’t receive any separator, but it is perfect for achieving the results we want in this article. However, if we need to have a separator between elements, we need to use a different approach.

We simply return the result of the Enumeraable.Aggregate(. ) method.

This method receives a Func delegate as a parameter to apply an accumulator over the array. This Func receives two variables as input parameters, prev and current . The prev represents the accumulator with all the previous elements, while the current represents each array value.

The Aggregate method efficiency depends on the accumulator function. In our case, we are using += operator. However, we could get more performance using the StringBuilder :

return array.Aggregate(new StringBuilder(), (prev, current) => prev.Append(current)).ToString();

Benchmark Comparison

We are going to run two benchmarks to check our method’s behavior against small and big arrays.

Let’s inspect the result against a small array, running the benchmark with an array of 1,000 elements:

private string[] _array = Enumerable.Repeat(«Code-Maze», 1_000).ToArray();

This difference is even more significant when we have a larger array:

As we can see in the benchmark results, when our array has 100,000 elements, the difference between the fastest approach achieves is more than 45,000 ms.

UsingStringConcat , UsingStringJoin , and UsingLoopStringBuilder use the StringBuilder class to concatenate the elements. On the other hand, UsingLoopStringAdditionAssignment and UsingAggregation concatenate the elements using the += operator. The benchmark results show that StringBuilder is much more efficient when dealing with strings.

How to convert string to string[]? [closed]

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 5 years ago .

The community reviewed whether to reopen this question 8 months ago and left it closed:

Original close reason(s) were not resolved

How to convert string type to string[] type in C#?

11 Answers 11

string[] is an array (vector) of strings string is just a string (a list/array of characters)

Depending on how you want to convert this, the canonical answer could be:

string[] -> string

string -> string[]

An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index (zero based).

Похожие статьи