C++,Java和Python中的字符串分割操作

0.C++

 

c++中采用strtok()函数分割字符串,函数调用形式为char *strtok(char s[], const char *delim);

 

strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。

 

例子:将I like China very much按空格分割:

#include<iostream>

#include<cstring>

using namespace std;

int main(){

    char *token_str[20];

    const int N = 5000;

    char test[N];

    cin.getline(test, N);

    int n = 0;

 

    token_str[n] = strtok(test, " ");

cout<<token_str[n]<<endl;

    while(token_str[n] != NULL){

        n++;

        token_str[n] = strtok(NULL, " ");

cout<<token_str[n]<<endl;

    }

    return 0;

}

 

输出结果为:I

                  like

               China

     very

                     much

 

 

 

 

1. Java

 

Java中采用split()函数分割字符串,语法:public String[] split(String regex, int limit);

 

·注意: . 、 | 和 * 等转义字符,必须得加 \\。

·注意:多个分隔符,可以用 | 作为连字符。

 

例子:

public class Test {

    public static void main(String args[]) {

        String str = new String("Welcome-to-Runoob");

 

        System.out.println("- 分隔符返回值 :" );

        for (String retval: str.split("-")){

            System.out.println(retval);

        }

 

        System.out.println("");

        System.out.println("- 分隔符设置分割份数返回值 :" );

        for (String retval: str.split("-", 2)){

            System.out.println(retval);

        }

 

        System.out.println("");

        String str2 = new String("www.runoob.com");

        System.out.println("转义字符返回值 :" );

        for (String retval: str2.split("\\.", 3)){

            System.out.println(retval);

        }

 

        System.out.println("");

        String str3 = new String("acount=? and uu =? or n=?");

        System.out.println("多个分隔符返回值 :" );

        for (String retval: str3.split("and|or")){

            System.out.println(retval);

        }

    }

}

 

输出结果为:

Welcome

to

runoob

 

www

runoob

com

 

acount=?

 uu =?

 n=?

 

 

2. Python

Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串,语法:str.split(str="", num=string.count(str));

 

例子:

str = "Line1-abcdef Line2-abc Line4-abcd";

print str.split( );

print str.split(' ', 1 );

 

输出结果为:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']

['Line1-abcdef', 'Line2-abc Line4-abcd']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值