Си шарп обрезать строку

Урок по работе со строками (String) на C#

Итак, на одном из прошлых занятий мы создали консольный калькулятор на си шарп. Итоговое значение калькулятора представляет собой число. Тип – int или double. Нам необходимо это число привести к такому виду, чтобы удобно было читать: отделять запятой по три значения – то есть каждый тысячный – миллионный и миллиардный разряды.

Например, предположим, в итоге у нас получилось число 345870124, требуется привести его к виду 345,870,124. Есть разные способы решения этой задачи, мы рассмотрим один из них и на примере его научимся работать со строками.

Прежде всего, нам надо число преобразовать в строку. Это можно сделать несколькими способами. Самый простой – это использовать метод ToString:

int itog = 345870124; String str = itog.ToString();

В этом случае компилятор сам автоматически создаст пустую строку, а при конкатенации числа с этой пустой строкой результат также автоматически будет строкой.

Итак, строку мы получили. Теперь необходимо вставить в неё запятые в нужных местах. Для этого надо использовать функцию Insert: Insert (“индекс элемента”, ”строка”); То есть, в нашем конкретном случае это будет выглядеть так:

String itog_str = str.Insert(3, ","); itog_str = itog_str.Insert(7, ",");

Что мы сделали? Мы вставили после третьего символа запятую в первой строке кода, а во второй – после седьмого. Почему после седьмого? Потому, что после вставки у нас увеличилась длина.

Казалось бы, задача решена? Не совсем. Дело в том, что мы сейчас имеем дело с определённым числом, а что если оно будет другим. Например, таким:

int itog = 1000000; String str = itog.ToString(); String itog_str = str.Insert(3, ","); itog_str = itog_str.Insert(7, ",");

И получим мы вот такую строку в результате: 100,000,0. Почему так получилось? Просто мы считали с начала строки индекс, а необходимо работать с конца. Для этого надо для начала найти длину строки:

int dlinaStroki = str.Length;

Теперь, зная длину, просто вычитаем из неё три и вставляем запятую:

String itog_str = str.Insert(dlinaStroki - 3, ",");

Это для отделения тысяч. А миллионов?

String itog_str = str.Insert(dlinaStroki - 3, ","); itog_str = itog_str.Insert(dlinaStroki - 6, ",");

Аналогично можно продолжить и выше. Для чисел типа int этого вполне хватит, но есть и другие. Обертка BigInteger или хотя бы long, ulong. Вот что делать с таким числом:

ulong itog = 10000000000000000000;

А все просто. Находим длину его, делим на три и циклом проходим столько раз, сколько надо:

ulong itog = 10000000000000000000; String str = itog.ToString(); int dlinaStroki = str.Length; int prohod = (dlinaStroki-1) / 3; for (int i = 1; i Console.WriteLine(str); Console.ReadKey();

Работает. Причем с числами любой длины: от единицы и до бесконечности. Теоретически.

Читайте также:  Java list remove all but one

Интересный момент: мы из длины строки вычитаем единицу, перед тем, как разделить её на три. Зачем это делается? Дело в том, что если этого не сделать, то у нас получается лишний последний проход и будет запятая перед числом – особенности целочисленного деления.

Задачу мы решили. Но еще познакомимся с парой методов для строк, которые могут быть полезны и стоит их знать любому программисту.

Обрезать определенную часть строки позволяет функция Substring:

String txt = "Игра продолжается"; // обрезаем начиная с пятого символа txt = txt.Substring(4); // результат "продолжается" Console.WriteLine(text);

С помощью метода IndexOf мы можем определить индекс первого вхождения отдельного символа или подстроки в строке:

String st = "Привет, друг"; char ch = 'т'; int indexOfChar = st.IndexOf(ch); // равно 5 Console.WriteLine(indexOfChar);

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

заметки, си шарп, строки, string

Бесплатный https и
домен RU в подарок

Источник

Trim and remove characters from strings in .NET

If you’re parsing a sentence into individual words, you might end up with words that have blank spaces (also called white spaces) on either end of the word. In this situation, you can use one of the trim methods in the System.String class to remove any number of spaces or other characters from a specified position in the string. The following table describes the available trim methods:

Method name Use
String.Trim Removes white spaces or characters specified in an array of characters from the beginning and end of a string.
String.TrimEnd Removes characters specified in an array of characters from the end of a string.
String.TrimStart Removes characters specified in an array of characters from the beginning of a string.
String.Remove Removes a specified number of characters from a specified index position in a string.

Trim

You can easily remove white spaces from both ends of a string by using the String.Trim method, as shown in the following example:

String^ MyString = " Big "; Console::WriteLine("HelloWorld!", MyString); String^ TrimString = MyString->Trim(); Console::WriteLine("HelloWorld!", TrimString); // The example displays the following output: // Hello Big World! // HelloBigWorld! 
string MyString = " Big "; Console.WriteLine("HelloWorld!", MyString); string TrimString = MyString.Trim(); Console.WriteLine("HelloWorld!", TrimString); // The example displays the following output: // Hello Big World! // HelloBigWorld! 
Dim MyString As String = " Big " Console.WriteLine("HelloWorld!", MyString) Dim TrimString As String = MyString.Trim() Console.WriteLine("HelloWorld!", TrimString) ' The example displays the following output: ' Hello Big World! ' HelloBigWorld! 

You can also remove characters that you specify in a character array from the beginning and end of a string. The following example removes white-space characters, periods, and asterisks:

using System; public class Example < public static void Main() < String header = "* A Short String. *"; Console.WriteLine(header); Console.WriteLine(header.Trim( new Char[] < ' ', '*', '.' >)); > > // The example displays the following output: // * A Short String. * // A Short String 
Module Example Public Sub Main() Dim header As String = "* A Short String. *" Console.WriteLine(header) Console.WriteLine(header.Trim()) End Sub End Module ' The example displays the following output: ' * A Short String. * ' A Short String 

TrimEnd

The String.TrimEnd method removes characters from the end of a string, creating a new string object. An array of characters is passed to this method to specify the characters to be removed. The order of the elements in the character array doesn’t affect the trim operation. The trim stops when a character not specified in the array is found.

Читайте также:  Получить имя объекта java

The following example removes the last letters of a string using the TrimEnd method. In this example, the position of the ‘r’ character and the ‘W’ character are reversed to illustrate that the order of characters in the array doesn’t matter. Notice that this code removes the last word of MyString plus part of the first.

String^ MyString = "Hello World!"; array^ MyChar = ; String^ NewString = MyString->TrimEnd(MyChar); Console::WriteLine(NewString); 
string MyString = "Hello World!"; char[] MyChar = ; string NewString = MyString.TrimEnd(MyChar); Console.WriteLine(NewString); 
Dim MyString As String = "Hello World!" Dim MyChar() As Char = Dim NewString As String = MyString.TrimEnd(MyChar) Console.WriteLine(NewString) 

This code displays He to the console.

The following example removes the last word of a string using the TrimEnd method. In this code, a comma follows the word Hello and because the comma isn’t specified in the array of characters to trim, the trim ends at the comma.

String^ MyString = "Hello, World!"; array^ MyChar = ; String^ NewString = MyString->TrimEnd(MyChar); Console::WriteLine(NewString); 
string MyString = "Hello, World!"; char[] MyChar = ; string NewString = MyString.TrimEnd(MyChar); Console.WriteLine(NewString); 
Dim MyString As String = "Hello, World!" Dim MyChar() As Char = Dim NewString As String = MyString.TrimEnd(MyChar) Console.WriteLine(NewString) 

This code displays Hello, to the console.

TrimStart

The String.TrimStart method is similar to the String.TrimEnd method except that it creates a new string by removing characters from the beginning of an existing string object. An array of characters is passed to the TrimStart method to specify the characters to be removed. As with the TrimEnd method, the order of the elements in the character array doesn’t affect the trim operation. The trim stops when a character not specified in the array is found.

Читайте также:  Php align image with text

The following example removes the first word of a string. In this example, the position of the ‘l’ character and the ‘H’ character are reversed to illustrate that the order of characters in the array doesn’t matter.

String^ MyString = "Hello World!"; array^ MyChar = ; String^ NewString = MyString->TrimStart(MyChar); Console::WriteLine(NewString); 
string MyString = "Hello World!"; char[] MyChar = ; string NewString = MyString.TrimStart(MyChar); Console.WriteLine(NewString); 
Dim MyString As String = "Hello World!" Dim MyChar() As Char = Dim NewString As String = MyString.TrimStart(MyChar) Console.WriteLine(NewString) 

This code displays World! to the console.

Remove

The String.Remove method removes a specified number of characters that begin at a specified position in an existing string. This method assumes a zero-based index.

The following example removes 10 characters from a string beginning at position five of a zero-based index of the string.

String^ MyString = "Hello Beautiful World!"; Console::WriteLine(MyString->Remove(5,10)); // The example displays the following output: // Hello World! 
string MyString = "Hello Beautiful World!"; Console.WriteLine(MyString.Remove(5,10)); // The example displays the following output: // Hello World! 
Dim MyString As String = "Hello Beautiful World!" Console.WriteLine(MyString.Remove(5, 10)) ' The example displays the following output: ' Hello World! 

Replace

You can also remove a specified character or substring from a string by calling the String.Replace(String, String) method and specifying an empty string (String.Empty) as the replacement. The following example removes all commas from a string:

using System; public class Example < public static void Main() < String phrase = "a cold, dark night"; Console.WriteLine("Before: ", phrase); phrase = phrase.Replace(",", ""); Console.WriteLine("After: ", phrase); > > // The example displays the following output: // Before: a cold, dark night // After: a cold dark night 
Module Example Public Sub Main() Dim phrase As String = "a cold, dark night" Console.WriteLine("Before: ", phrase) phrase = phrase.Replace(",", "") Console.WriteLine("After: ", phrase) End Sub End Module ' The example displays the following output: ' Before: a cold, dark night ' After: a cold dark night 

See also

Feedback

Submit and view feedback for

Источник

Оцените статью