Java 字符串中出现第n个字符并获取值
我使用下面的代码查找字符串中第n次出现的Java 字符串中出现第n个字符并获取值,java,string,find-occurrences,Java,String,Find Occurrences,我使用下面的代码查找字符串中第n次出现的,(逗号)。一旦我得到这个,我需要得到这个事件(n次)和下一个事件(n+1次)之间的值 如果我有什么地方出错,请告诉我 int ine=nthOccurence(line,18); String strErrorCode=line.substring(ine,line.indexOf(",", ine+1)); String errorCode=strErrorCode.substring(1, strErrorCode.lengt
,
(逗号)。一旦我得到这个,我需要得到这个事件(n次)和下一个事件(n+1次)之间的值
如果我有什么地方出错,请告诉我
int ine=nthOccurence(line,18);
String strErrorCode=line.substring(ine,line.indexOf(",", ine+1));
String errorCode=strErrorCode.substring(1, strErrorCode.length());
功能
public static int nthOccurence(String strLine,int index)
{
char c=',';
int pos = strLine.indexOf(c, index);
while (index-- > 0 && pos != -1)
{
pos = strLine.indexOf(c, pos+1);
// System.out.println("position is " + pos);
}
return pos;
}
谢谢。这里有另一种方法,也更具可读性:
public static String getAt(String st, int pos) {
String[] tokens = st.split(",");
return tokens[pos-1];
}
public static void main(String[] args) {
String st = "one,two,three,four";
System.out.println(getAt(st, 1)); // prints "one"
System.out.println(getAt(st, 2)); // prints "two"
System.out.println(getAt(st, 3)); // prints "three"
}
以下是另一种更具可读性的方法:
public static String getAt(String st, int pos) {
String[] tokens = st.split(",");
return tokens[pos-1];
}
public static void main(String[] args) {
String st = "one,two,three,four";
System.out.println(getAt(st, 1)); // prints "one"
System.out.println(getAt(st, 2)); // prints "two"
System.out.println(getAt(st, 3)); // prints "three"
}
像这样的
public static int nthOccurence(String strLine,int index){
String[] items = strLine.split(",");
if (items.length>=index)
return items[index];
else
return "";//whatever you want to do it there's not enough commas
}
像这样的
public static int nthOccurence(String strLine,int index){
String[] items = strLine.split(",");
if (items.length>=index)
return items[index];
else
return "";//whatever you want to do it there's not enough commas
}
我很困惑。字符串errorCode=strErrorCode.substring(1,strErrorCode.length())应该完成吗?返回的字符串开头包含-。我需要删除它。因此,带有两个
int
参数的。[substring
(,int))使用第一个(from)作为包含,第二个(to)作为独占。这与你对“中间”的定义一致吗?但是代码正确吗?我的意思是我得到了可变的输出。我不能在指数上下注。我很困惑。字符串errorCode=strErrorCode.substring(1,strErrorCode.length())应该完成吗?返回的字符串开头包含-。我需要删除它。因此,带有两个int
参数的。[substring
(,int))使用第一个(from)作为包含,第二个(to)作为独占。它与你对“中间”的定义一致吗?但是代码正确吗?我的意思是我得到了可变的输出。我不能在指数上下注。我不确定你的意思。你是说你需要字符串中的位置吗?开始位置、结束位置或两者。你有没有在里面加逗号。你需要更清楚些,我不知道你的意思。你是说你需要字符串中的位置吗?开始位置、结束位置或两者。你有没有在里面加逗号。你需要更清楚。