如何在相同位置的字符串中找到不同的字符?例如:
String string1 = "Anand has 2 bags and 4 apples";
String n = /* ??? */;
String n2 = /* ??? */;
String string2 = "Anand has " + n + " bags and " + n2 + " apples";
我想要n = "2"
和n1 = "4"
。
请告诉我们怎么做? (为了清晰起见,在单词之间添加空格。但我不能使用Space作为分隔符)
答案 0 :(得分:1)
您可以使用for循环遍历较小字符串的长度并单独检查每个位置
答案 1 :(得分:1)
如果您确定字符串中的文字保持不变,您可以执行以下操作 -
String string1 ="Anand has 2 bags and 4 apples";
String[] parts = string1.split("\\s+");
System.out.println("n = " + parts[2] + " n1 = " + parts [5]);
答案 2 :(得分:0)
正则表达式应该很好地完成。
答案 3 :(得分:0)
如果长度不同:
for(int i = 0; i < Math.min(str1.length, str2.length); i++){
if(str1.charAt(i) != str2.charAt(i)){
//Different
}
}
for(int i = Math.min(str1.length, str2.length);
i < Math.max(str1.length, str2.length); i++){
//Each is in one but not the other.
}
如果长度相同:
for(int i = 0; i < str1.length; i++){
if(str1.charAt(i) != str2.charAt(i)){
//Different
}
}
答案 4 :(得分:0)
我会用“空格”分割字符串,然后我会做一个for循环来查找结果数组中的数字。这是一个小例子,它是丛生的,但它完成了工作:
import java.util.ArrayList;
public class XXX{
public static void main(String[] args){
String str = "Anand has 2 bags and 4 apples";
System.out.println("Start...");
System.out.println(str);
String words[] = str.split("\\s+");
ArrayList<String> values = new ArrayList<String>();
for(String s:words){
System.out.println(s);
try{
Integer.parseInt(s);
values.add(s);
}
catch(NumberFormatException ex){
System.out.println(s + " is not a number");
}
}
System.out.println("Anand has " + values.get(0) + " bags and " + values.get(1) + " apples");
}
}
答案 5 :(得分:0)
你可以使用我开发的StringTemplate类(我开发了一个URITemplate类来匹配restlike uris但是已经修改它以使用字符串)
// Licensed Apache2 (http://www.apache.org/licenses/LICENSE-2.0.txt)
import java.util.List;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <pre>
* StringTemplate t = new StringTemplate("/catalog/{categoryId}/products/{productId}/summary");
* t.matches("/catalog/23/products/12375/summary"); // returns true
* t.match("/catalog/23/products/12375/summary"); // returns a map {categoryId=23, productId=12375}
* </pre>
*
* @author anaik
*/
public class StringTemplate {
/** The meta pattern for template to match sequence such as: {someVar} */
private static final Pattern patternPattern = Pattern.compile("\\{([^\\{\\}]+)\\}");
/** The pattern string */
private String stringPattern;
/** The generated pattern when the stringPattern is parsed */
private Pattern thisStringPattern;
/** Variable names found in this pattern in that order */
private List<String> vars = new ArrayList<String>();
/**
* Creates a new StringTemplate from the specified pattern
* @param Pattern
*/
private StringTemplate(String stringPattern) {
this.stringPattern = stringPattern;
initialize();
}
/**
* Gets the names of variables - those defined in {variable-name} constructs - in this StringTemplate
* in the order they were specified
* @return a list of variables or an empty list if no variables were found
*/
public List<String> getVars() {
return vars;
}
/**
* Determine whether the specified <tt>actualString</code> matches with this StringTemplate
* @param actualString The actual to match
* @return true iff successfull match
*/
public boolean matches(String actualString) {
return thisStringPattern.matcher(actualString).matches();
}
/**
* Matches the <tt>actualString</tt> with this StringTemplate and extracts values for all the variables
* in this template and returns them as an ordered map (keys defined in the same order as that of
* the StringTemplate. If the match was unsuccessfull, an empty map is returned. Note that this method
* should be ideally be called after {@link #matches(java.lang.String) } to check whether the
* specified actually matches the template
*/
public Map<String, String> match(String actualString) {
Matcher m = thisStringPattern.matcher(actualString);
Map<String, String> map = new LinkedHashMap<String, String>();
if(m.matches()) {
int gc = m.groupCount();
for(int i = 0; i < gc; i++) {
int g = i + 1;
map.put(vars.get(i), actualString.substring(m.start(g), m.end(g)));
}
}
return map;
}
private void initialize() {
Matcher m = patternPattern.matcher(stringPattern);
StringBuffer builder = new StringBuffer();
while(m.find()) {
String var = m.group(1);
vars.add(var);
m.appendReplacement(builder, "(.*)");
}
m.appendTail(builder);
String genPattern = builder.toString();
thisStringPattern = Pattern.compile(genPattern);
}
public static void main(String[] args) throws Throwable {
StringTemplate t = new StringTemplate(args[0]);
System.out.println("Matches with actual Class Identifier: java.lang.String: " + t.matches(args[1]));
System.out.println("Var values: " + t.match(args[1]));
}
}
编译并测试如下:
tmp$ java StringTemplate "Anand has {n} bags and {n1} apples" "Anand has 23 bags and 500 apples"
这是输出
Matches with actual URI: true
Var values: {n=23, n1=500}
matches(String)返回包含模板变量名称和值的映射。 此类可用于将任何字符串与任意数量的变量匹配。它的liscensed apache2
如果您的输入字符串包含正则表达式字符,则必须将它们转义:
input = input.replaceAll("\\$", "\\\\\\$");
input = input.replaceAll("\\(", "\\\\(");
input = input.replaceAll("\\)", "\\\\)");
StringTemplate st = new StringTemplate(input);
请注意,对于输入字符串已包含“\ $”等字符的条件,您需要更准确的regexx