[英]Substring a string based on presence of a character
I have a string: LOAN,NEFT,TRAN
. 我有一个字符串: LOAN,NEFT,TRAN
。 I want to substring the string based on getting a ,
during traversing the string. 我想串基础上得到一个字符串,
遍历字符串中。 So I tried to first get a count for how many ,
are there. 于是,我就先得到多少的计数,
在那里。 but not sure what function to user to get what I want. 但不确定用户要获得我想要的功能是什么。 Also this should be dynamic, meaning I should be able to create as many substrings as required based on number of ,
s. 这也应该是动态的,这要求基础上的号码,我应该能够创造尽可能多的子串,
秒。 I tried the following code: 我尝试了以下代码:
package try1;
public class StringTest {
public static void main(String[] args) {
String str="LOAN,NEFT,TRAN";
int strlen=str.length();
int count=0;
for(int i=0;i<strlen;i++)
{
if(str.contains("'"))
count++;
}
System.out.println(""+count);
for (int j=0;j<count;j++)
{
//code to create multiple substrings out of str
}
}
}
But I do not think contains()
is the function I am looking for because value of count here is coming 0. What should I use? 但是我不认为contains()
是我要查找的函数,因为count的值即将变为0。我应该使用什么?
You can use split to get substrings directly: 您可以使用split直接获取子字符串:
String[] substrings = str.split(",");
Is this what you want as an output: (shown below)? 这是您想要的输出:(如下所示)吗?
["LOAN", "NEFT", "TRAN"] // Array as an output
Or to just get the count of the splitting char, you can use the same line as above with this: 或仅获取拆分字符的计数,您可以使用上面的同一行:
int count = substrings.length - 1;
Your code doesn't actually count the , characters because 1) contains doesn't take into account your loop variable 2) it's searching for ', not , 您的代码实际上并未计算,字符,因为1)包含的内容未考虑您的循环变量2)它在搜索',不是,
Assuming you want to work at a low level rather than using high level functions like .split(), then I'd recommend the following. 假设您想以较低级别工作,而不是使用诸如.split()之类的高级函数,那么我建议以下内容。
for(char c : str.toCharArray()) {
if (c == ',') {
count++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.