在Java中减去外部String中的内部字符串

时间:2011-03-09 22:22:41

标签: java string

我想知道是否有办法根据用户的选择减去Java中另一个字符串中包含的字符串。

这是我的代码:

removeIng = pH1 + pH2 + pH3;  
System.out.print("Enter number corresponding to element you want to remove");  
System.out.printf("%s",removeIng);  
remove = in.nextInt();  
switch(remove)  
{  
case 1:  
    removeIng = pH2 + pH3;  
case 2:  
    removeIng = pH1 + pH3;  
case 3:  
    removeIng = pH1 + pH2;  
}  

我需要动态代码,以便用户可以根据需要删除所有元素。我已经创建了一个外部循环以允许这种可能性。但我不知道如何让“removeIng”减去用户选择的元素。我可以弄清楚其他部分。任何帮助将不胜感激。我已经找到了减去声称为“blah blah”的字符串的方法,但不是这样的。希望这是有道理的。

感谢。

1 个答案:

答案 0 :(得分:0)

根据您的示例代码,可能更容易跟踪用户不想要的字符串的哪些位,并基于此生成removeIng。这是一些伪代码。我牺牲了优化以支持清晰度:

String[] components;
// what used to be called pH1 is accessed by components[0];
boolean[] deletedPieces;
// initially set to all false
// contains true for segments that the user wants to delete, false otherwise

your outer loop here {
    // ask the user which piece to delete here
    remove = in.nextInt() - 1; // - 1 to account for array indices starting at 0

    deletedPieces[remove] = true;

    StringBuilder sb = new StringBuilder();

    for(int i = 0; i < total number of possible pieces; i++) {
        if(deletedPieces[i])
            // user wanted this piece deleted; do nothing
        else
            sb.append(components[i]);
    }

    removeIng = sb.toString();
}