Java 如何拆分以逗号分隔的字符串,该字符串包含带逗号的括号内的子字符串
以下是我的例子:Java 如何拆分以逗号分隔的字符串,该字符串包含带逗号的括号内的子字符串,java,Java,以下是我的例子: 输入: String str="hello,there,(what,is,new),today,(with,you)" 期望输出: hello there (what,is,new) today (with,you) 我认为最简单的方法是在for循环中逐个字符地遍历字符串,并用空格替换逗号,除非您在括号内(您需要保留它们的数量)现在它可以工作了 String str="hello,there,(what,is,new),today,(with,you)"; int insi
输入:
String str="hello,there,(what,is,new),today,(with,you)"
期望输出:
hello
there
(what,is,new)
today
(with,you)
我认为最简单的方法是在for循环中逐个字符地遍历字符串,并用空格替换逗号,除非您在括号内(您需要保留它们的数量)现在它可以工作了
String str="hello,there,(what,is,new),today,(with,you)";
int inside = 0;
int index = 0;
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) == ')'){
inside--;
}else if (str.charAt(i) == '('){
inside++;
}else if (str.charAt(i) == ',' && inside == 0){
System.out.println(str.substring(index, i));
index = i+1;
}
}if (index != str.length()){
System.out.println(str.substring(index, str.length()));
}
String str=“你好,(什么,是新的),今天,(和你一起)”;
内部整数=0;
int指数=0;
对于(int i=0;i
ArrayList myList=new ArrayList();
int index1=-1;
int index2=0;
对于(int i=0;i
String str=“你好,这里,(什么,是新的),今天,(和你一起)”;
ArrayList myList=新的ArrayList();
int index1=-1;
int index2=0;
对于(int i=0;i 对于(int i=0;i显示您首先实现目标的尝试。String str=“你好,那里,(是什么,新的),今天,(和你一起)”;String[]tokens=str.split(\((!=[^\(*\)$))”);(String t:tokens){System.out.println(“>”+t);}>你好,那里,>什么,是新的),今天,>和你一起)这是我最新的尝试:
String str=“你好,(什么,是新的),今天,(和你一起)”;
字符串[]标记=str.split(,(?=[^\(*\)$)))”;(字符串t:tokens){System.out.println(“>”+t);}替代方法包括使用正则表达式库或解析器生成器来执行所述操作的形式化版本。那么,我建议先用Regexp将括号内的逗号替换为其他符号,然后用空格替换普通逗号,然后再将其他符号替换回逗号^ ^我不知道我不同意你的观点,只是指出如果OP有更复杂的情况,可以用于此目的的工具。啊,当然,对不起,我以为你对解决问题的允许方法发表了评论:)谢谢。我尝试过,但没有起作用。我想更多的是使用正则表达式。现在检查一下。它是固定的,我相信它最终会起作用。a你要将子字符串存储到myList中吗?我得到了:hell ther(wha I new toda)(witfor(int I=0;ithanks),但这并不能产生所需的输出。我发现它看起来像我将要发布的内容。你可以将其作为解决方案,因为我将结果存储在一个文件中,而不仅仅是打印它
ArrayList<String> myList = new ArrayList<String>();
int index1=-1;
int index2=0;
for(int i=0;i< str.length;i++)
{
if(str.charAt(i) == ',')
{
index2=i;
myList.add(str.substring(index1+1 ,index2-1));
index1=index2;
}
}
String str="hello,there,(what,is,new),today,(with,you)";
ArrayList<String> myList = new ArrayList<String>();
int index1=-1;
int index2=0;
for(int i=0;i< str.length();i++)
{
if(str.charAt(i) != '(' ){
if(str.charAt(i) == ',' )
{
index2=i;
myList.add(str.substring(index1+1 ,index2));
index1=index2;
}
}
else
while(str.charAt(i)!=')')
i++;
}
for(int i=0;i<myList.size();i++) System.out.println(myList.get(i));