提取字符串,包括字符串中的空格(java)
我有一个字符串,它包含两个整数,由空格分隔,后跟任何包含空格的字符串 示例:提取字符串,包括字符串中的空格(java),java,string,whitespace,substring,extract,Java,String,Whitespace,Substring,Extract,我有一个字符串,它包含两个整数,由空格分隔,后跟任何包含空格的字符串 示例: 23 14 this is a random string 如何提取这是一个随机字符串 整数不能保证是两位数,因此我不知道如何使用indexOf和substring来提取这些数据 提前感谢。使用: 输出: 23 14 this is a random string 这是一个随机字符串 您可以使用StringTokenizer,如果您知道将有2个数字,只需忽略数组中的前两个元素 StringBuffer sb = n
23 14 this is a random string
如何提取这是一个随机字符串
整数不能保证是两位数,因此我不知道如何使用indexOf和substring来提取这些数据
提前感谢。使用:
输出:
23 14 this is a random string
这是一个随机字符串
您可以使用StringTokenizer,如果您知道将有2个数字,只需忽略数组中的前两个元素
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer("23 14 this is a random string");
int i = 1; // counter: we will ignore 1 and 2 and only append
while (st.hasMoreTokens()) {
// ignore first two tokens
if (i > 2) {
sb.append(st.nextToken()); // adds remaining strings to Buffer
}
i++; // increment counter
} // end while
// output content
sb.toString();
只用
StringTokenizer st=new StringTokenizer(youString, " "); //whitespaces as delimeter
int firstInteger=Integer.parseInt(st.nextToken());
int secondInteger=Integer.parseInt(st.nextToken());
类似地,其余的令牌
你可以做一个确定的数组
并将其余令牌存储在如下字符串数组中
while(st.hasMoreTokens())
{
ar[i]=st.nextToken();
}
老实说。。。如果您的
字符串
遵循某种模式,并且需要从中提取某些内容,请尝试使用Regex
。这是为这个而做的
Pattern regex = Pattern.compile("^\\d+ \\d+ (.*)$");
Matcher matcher = regex.matcher("23 14 this is a random string");
if (matcher.find())
System.out.println(matcher.group(1));
这将产生:
this is a random string
哇。我不敢相信有些人写了多少代码来做最简单的事情 这是一个优雅的单线解决方案:
String remains = input.replaceAll("^(\\d+\\s*){2}","");
这里有一个测试:
public static void main( String[] args ) {
// rest of String contains more numbers as an edge case
String input = "23 14 this is a random 45 67 string";
String remains = input.replaceAll("^(\\d+\\s*){2}","");
System.out.println( remains );
}
输出:
this is a random 45 67 string
我将使用上述答案的组合,
regex
+replaceFirst
String s = "23 14 this is a random string";
String formattedS = s.replaceFirst("\\d+ \\d+ ", "");
这将删除由空格分隔的前两个数字,而不管这些数字有多大。
exampleString.substring(exampleString.indexOf(“”,exampleString.indexOf(“”+1)+1)代码>您可以查看java.util.Scanner类这是最简单的解决方案,我认为您应该将其标记为答案。:)@Geoff顺便说一句,这不是最简单的解决方案(请参见我的),如果剩余文本为空(即输入为“12 34”
,这在问题中没有排除),则将使用ArrayIndexOutOfBounds爆炸,因为拆分中没有第三个元素。。如果“随机字符串”也包含数字呢?那么使用Eng Fouad的解决方案:
String s = "23 14 this is a random string";
String formattedS = s.replaceFirst("\\d+ \\d+ ", "");