Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 提取特定字符串变量之间的字符串_Java_String_Substring - Fatal编程技术网

Java 提取特定字符串变量之间的字符串

Java 提取特定字符串变量之间的字符串,java,string,substring,Java,String,Substring,我需要在两个特定的字符串变量之间提取一个字符串。例如,考虑字符串 X1-67 6Y1-44 Z188X2-623 Y2-67 Z27 4 < /代码>。现在我需要检测字符串中的x1和y1,获取x1和y1之间的所有数据,并将其存储为字符串而不是字符。同样,获取y1和z1之间以及其他变量的数据 下面是我尝试过的代码: bytes = mmInStream.read(buffer); String str = new String(buffer, "UTF-8"); // prints charact

我需要在两个特定的字符串变量之间提取一个字符串。例如,考虑字符串<代码> X1-67 6Y1-44 Z188X2-623 Y2-67 Z27 4 < /代码>。现在我需要检测字符串中的
x1
y1
,获取
x1
y1
之间的所有数据,并将其存储为字符串而不是字符。同样,获取
y1
z1
之间以及其他变量的数据

下面是我尝试过的代码:

bytes = mmInStream.read(buffer);
String str = new String(buffer, "UTF-8"); // prints character
Log.d("Data Transmitted", str);

StringBuffer sb = new StringBuffer(str);
int a=sb.indexOf("x1");
char x1=sb.charAt(a+1);
System.out.println(x1);

int b=sb.indexOf("y1");
char y1=sb.charAt(b+1);
System.out.println(y1);

您可以使用
子字符串
方法:

int x1pos = str.indexOf("x1");
int y1pos = str.indexOf("y1");
if (x1pos >= 0 && x1pos <= str.length() - 2 && y1pos >= 0 && y1pos > x1pos) {
    String between = str.substring(x1pos+2,y1pos);
}
else {
    //do something else
}
intx1pos=str.indexOf(“x1”);
int y1pos=str.indexOf(“y1”);
如果(x1pos>=0&&x1pos=0&&y1pos>x1pos){
字符串之间=str.substring(x1pos+2,y1pos);
}
否则{
//做点别的
}

您尝试了什么?是的。编写代码。字符串有很好的方法:intindexof(stringstr)你有一个很好的开始。我会使用正则表达式,但这应该很好。是的,它工作了。但现在它在输出中使用x1。我只需要x1和y1之间的字符串。你认为是+1吗?是的,现在我得到了所需的输出。谢谢。我这样做是因为s.substring(s.indexOf(“A”)+1,s.indexOf(“B”))Javadoc是你的朋友。
int x1pos = str.indexOf("x1");
int y1pos = str.indexOf("y1");
if (x1pos >= 0 && x1pos <= str.length() - 2 && y1pos >= 0 && y1pos > x1pos) {
    String between = str.substring(x1pos+2,y1pos);
}
else {
    //do something else
}