1.Introduction
Strings are one of the most interesting parts of the software development. We usually get input from a user as a string then process it to obtain the results. Dealing with the strings is a bit tricky so we need to know ways to handle frequent problems. Splitting a string(also known as tokenizing a string) can be perceived as dividing it into parts which we are more interested. Suppose that you need to extract words from a sentence where these words are separated by comma . You need an efficient and simple way to get the part you are interested in — the words — . Same thing applies for other types, you may need to extract numbers, special characters and even whitespaces. In this article, we will inspect the methods we can use when we need to split a string.
2.Logic of Splitting a String
We need to know essentials of this process:
String: The string we need to split.
Delimiter: The character or characters, even maybe another string that be used to divide the string from wherever it is found.
Given a string with different characters below and assume that our delimiter is the comma(‘,’) character :
The splitted string would be like this:
Where strings in each row represents a token. Now, if you have figured it out, we can continue with the implementations.
3.Using C++ Built-in(Native) Functions
C++ has dozens of functions that are dedicated for string operations. Also, to split a string, you can combine these functions.
3.1.Using strtok() function
This function exists in a C library which is named “string.h” or <cstring> in C++. You can also use it in C++, but first you have to convert C++ string to classical C string since it is a C function, then, you can convert it back to C++ string.
The strtok() Prototype and Explanation:
It returns the token, takes string and delimiters as input. For the first call, you need to pass a string for the first argument. But then, you have to pass a null pointer every time to continue splitting.
Algorithm:
Code:
Output:
3.2.Using string::rfind() function with string::substr() function
We can use string::rfind() function with string::substr() function. We use string::rfind() function to find the position of the delimiter(s) which we are interested in, starting from right(or reverse) and string::substr() function to create the substring which is the token itself and erase the found token from string.
Algorithm:
Code:
Output:
3.3.Using string::rfind() function with string::substr() function and string::erase() function
It is similar to 3.2. except we use string::erase() which is an inplace function to erase a part of a string. First argument for erase() function is position and second argument is the length for spanning. In example, if first parameter is 0 and second parameter is 8, it starts from position 0 and erases the 8 characters after this position.
Algorithm:
Code:
Output:
3.4.Using string::find() function with string::substr() function
We can use string::find() function with string::substr() function. We use string::find() function to find the position of the delimiter(s) which we are interested in, starting from left(or beginning) and string::substr() function to create a substring which is the token itself and erase the found token from string.
Algorithm:
Code:
Output:
3.5.Using stringstream with getline() function
We can create a stringstream object with our string and separate it using getline().
Algorithm:
Code:
Output:
4.Storing Tokens
After we have splitted the string, we may need to store them in an array, avector, or a list or any other data structure.
Как разделить строку по пробелам 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
In C#, Split() is a string class method. The Split() method returns an array of strings generated by splitting of original string separated by the delimiters passed as a parameter in Split() method. The delimiters can be a character or an array of characters or an array of strings. Or you can also say that it returns a string array which contains the substrings in the current instance that are delimited by elements of a specified string or Unicode character array.
There are 6 methods in the overload list of this method as follows:
| Method | Description |
|---|---|
| Split(String[], Int32, StringSplitOptions) | Split string into maximum number of sub strings based on the array of strings passed as parameter. You can specify whether to include the empty array elements in array of sub strings or not. |
| Split(Char[], Int32, StringSplitOptions) | Split string into maximum number of sub strings based on the array of characters passed as parameter. You can specify whether to include the empty array elements in array of sub strings or not. |
| Split(String[], StringSplitOptions) | Splits a string into substrings based on the array of strings. You can specify whether to include the empty array elements in array of sub strings or not. |
| Split(Char[]) | Splits a string into substrings based on the array of characters. |
| Split(Char[], StringSplitOptions) | Splits a string into substrings based on the array of characters. You can specify whether to include the empty array elements in array of sub strings or not. |
| Split(Char[], Int32) | Split string into maximum number of sub strings based on the array of characters passed as parameter. You can specify maximum number of sub strings to return. |
1. Split(String[], Int32, StringSplitOptions) Method
This method is used to splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements.
Syntax:
Parameters:
- separator: It is a string array which delimits the substrings in this string, an empty array that contains no delimiters, or null.
- count: It is the maximum number of substring to return.
- options:RemoveEmptyEntries option to omit empty array elements from the array returned or None option to include empty array elements in the array returned.
Return: This method returns an array whose elements contain the substrings in this string which are delimited by one or more characters in the separator.
Split string in C every white space
I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what I have done so far:
Although the output is what I want, I have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end. I can understand that there is a mistake at my malloc() implementation, but I do not know what it is.
Is there another more elegant or generally better way to do it?
![]()
9 Answers 9
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
- str
- C string to truncate.
- Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
- C string containing the delimiter characters.
- These may vary from one call to another.
Return Value
A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.