我在替换短语中的某些字符串时遇到了问题。我必须将"_“替换为和"< / I>”交替。到目前为止我的代码如下:
private String line; //The line to format
public TextFormatter(String lineToFormat) {
line = lineToFormat;
}
/**
* Finds the first single instance of str in line, starting at the postion start
* <p>
* @param str the string of length 1 to find. Guaranteed to be length 1.
* @param start the position to start searching. Guaranteed to be in the string line.
* <p>
* @return the index of first instance of str if string found or -1 otherwise.
*/
private int findString(String str, int start) {
String phrase = line;
int psn = phrase.indexOf(str, start);
return psn;
}
/**
* Count the number of times single instances of str appear in the line.
* <p>
* @param str the string to find. Guaranteed to be length 1.
* <p>
* @return the number of times the string appears in the line.
*/
private int countStrings(String str) {
int counter = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '_') {
counter++;
}
}
return counter;
}
/**
* Replaces all single instances of underscores in the line given by line with italics tags. There must be an even
* number of underscores in the line, and they will be replaced by <I>, </I>, alternating.
* <p>
* @return the line with single instances of underscores replaced with
* <I> tags or the original line if there are not an even number of underscores.
* <p>
*/
public String convertItalics() {
String toReturn = " ";
if (countStrings("_") % 2 == 0) { //makes sure there is even number of "_"
for (int i = 0; i < line.length(); i++) {
if (line.indexOf("_") + i == line.indexOf("_")) {
toReturn += line.replace("_", "<I>");
}
}
} else if (countStrings("_") % 2 != 0) {
toReturn += line.replace("_", " ");
}
return toReturn;
}我已经掌握了第一个方法,但是我在使用convertItalics()时遇到了问题。如果我运行我的代码,我会让它替换"_“,但它不会替换。
如果我有像"hello _my name is _chomez_“这样的短语,它不会替换任何"_”。任何帮助都将不胜感激。谢谢!
编辑:感谢那些留下评论的人,我的课程快结束了,所以我会在有电脑使用和有时间的时候再来看看,谢谢大家!
发布于 2014-12-13 00:41:39
如果你想替换Java中的字符,我建议使用" replace“方法,例如:
public class Test{
public static void main(String args[]){
String Str = new String("This is a long string");
System.out.println(Str.replace('i', 'o'));这基本上会将"i“替换为"o”。此外,如果要比较java中的字符串,则必须使用equals或equalsIgnoreCase而不是==方法,因为您要比较的是字符的数量和正确的顺序,而不是这些字符串的值。
我希望这能对你有所帮助!
https://stackoverflow.com/questions/27447972
复制相似问题