个性化阅读
专注于IT技术分析

如何在C/C++,Python和Java中分割字符串?

点击下载

用一些定界符分割字符串是非常常见的任务。例如, 我们用逗号分隔文件中的项目列表, 并且希望将单个项目放在数组中。

几乎所有的编程语言, 都提供通过某些定界符分割字符串的功能。

在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;
}

输出如下:

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-Geeks

Geeks
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)。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

赞(0)
未经允许不得转载:srcmini » 如何在C/C++,Python和Java中分割字符串?

评论 抢沙发

评论前必须登录!