难以在分隔符处拆分字符串并保留它

时间:2016-12-13 19:36:38

标签: java regex string split

我有一对成对读取的字符串,以逗号分隔。但是,我并不总是想用逗号分割,因为输入中并不总是有1个逗号。例如,字符串

(http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b
,http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6,file:///tmp/foo/bar/p,d,f.pdf)

全部读一行。对于这种情况,我只想在字符串中的,h和no处分开。基本上,在拆分之后,字符串应为:

http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b

http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6

file:///tmp/foo/bar/p,d,f.pdf

维护第一个字符串中逗号的顺序。 (我将摆脱括号)。我查看了this堆栈溢出问题,虽然有用,但没有正确拆分此字符串。这是Java。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:5)

您可以使用正则表达式进行拆分。请参阅下面的代码段。

String str = "(http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b,http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6)";
String[] strArr = str.split("(,(?=http))");

根据您的要求,您将拥有所有可能值的数组。

答案 1 :(得分:1)

拆分' http'然后重新添加它。

伪代码

#include<iostream>

using namespace std;

struct Node
{
    int num;
    Node *next;
};

Node *head = NULL;
Node *tail = NULL;

void AddnodeAtbeggining(){
    Node *temp = new Node;
    cout << "Enter the item";
    cin >> temp->num;
    temp->next = NULL;
    if (head == NULL)
    {
        head = temp;
        tail = temp;
    }
    else
    {
        temp->next = head;
        head = temp;
    }
}

void addnodeAtend()
{
    Node *temp = new Node;
    cout << "Enter the item";
    cin >> temp->num;
    temp->next = NULL;
    if (head == NULL){
        head = temp;
        tail = temp;
    }
    else{
        tail->next = temp;
        tail = temp;
    }
}

void displayNode()
{
    cout << "\nDisplay Function\n";
    Node *temp = head;
    for(Node *temp = head; temp != NULL; temp = temp->next)
        cout << temp->num << ",";
}

void deleteNode ()
{
    for (Node *temp = head; temp != NULL; temp = temp->next)
        delete head;
}

int main ()
{
    AddnodeAtbeggining();
    addnodeAtend();
    displayNode();
    deleteNode();
    displayNode();
}

Final应包含两个网址。