用一些定界符分割字符串是非常常见的任务。例如, 我们用逗号分隔文件中的项目列表, 并且希望将单个项目放在数组中。
几乎所有的编程语言, 都提供通过某些定界符分割字符串的功能。
在C/C++中:
//Splits str[] according to given delimiters.
//and returns next token. It needs to be called
//in a loop to get all tokens. It returns NULL
//when there are no more tokens.
char * strtok(char str[], const char *delims);
//A C/C++ program for splitting a string
//using strtok()
#include <
stdio.h>
#include <
string.h>
int main()
{
char str[] = "Geeks-for-Geeks" ;
//Returns first token
char *token = strtok (str, "-" );
//Keep printing tokens while one of the
//delimiters present in str[].
while (token != NULL)
{
printf ( "%s\n" , token);
token = strtok (NULL, "-" );
}return 0;
}
【如何在C/C++,Python和Java中分割字符串()】输出如下:
Geeks
for
Geeks
在Java中:
在Java中, split()是String类中的方法。
//expregexp is the delimiting regular expression;
//limit is the number of returned strings
public String[] split(String regexp, int limit);
//We can call split() without limit also
public String[] split(String regexp)
//A Java program for splitting a string
//using split()
import java.io.*;
public class Test
{
public static void main(String args[])
{
String Str = new String( "Geeks-for-Geeks" );
//Split above string in at-most two strings
for (String val: Str.split( "-" , 2 ))
System.out.println(val);
System.out.println( "" );
//Splits Str into all possible tokens
for (String val: Str.split( "-" ))
System.out.println(val);
}
}
输出如下:
Geeks
for-GeeksGeeks
for
Geeks
在Python中:
//regexp is the delimiting regular expression;
//limit is limit the number of splits to be made
str.split(regexp = "", limit = string.count(str))
line = "Geek1 \nGeek2 \nGeek3" ;
print line.split()
print line.split( ' ' , 1 )
输出如下:
['Geek1', 'Geek2', 'Geek3']
['Geek1', '\nGeek2 \nGeek3']
本文作者:阿蒂亚(Aditya Chatterjee)。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。
推荐阅读
- xp系统如何管理网络密码?xp网络密码如何查看?
- 如何在Golang中分割字节切片()
- 如何在Golang中对整数进行排序()
- 如何在C++中使用STL对数组进行排序()
- 如何在C/C++中对日期数组进行排序()
- 如何在C++中使用STL按降序对数组排序()
- 如何在C#中对数组排序Array.Sort()|S1
- 如何对链表进行排序,该列表按升序和降序交替排序()
- 如何对很多重复的大数组进行排序()