替换短语中的字符串时遇到问题

时间:2014-12-12 16:31:25

标签: java

我无法替换短语中的某些字符串。我必须更换" _"与<我>和"< / 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()的问题。 如果我运行我的代码,我会让它替换&#34; _&#34;但它并没有交替。

如果我有一个像&#34;你好_my名字是_chomez _&#34;这样的短语,它就不会取代任何&#34; _&#34;。任何帮助,将不胜感激。谢谢!

编辑:感谢那些发表评论的人,我的班级已经快结束了,所以当我有权使用计算机时,我会回来查看,我有时间,谢谢大家!

4 个答案:

答案 0 :(得分:0)

我在这行上做了评论,我建议从一行创建一个字符串数组并循环该行。 像

这样的东西
String [] words = line.split(" ");

然后循环播放这些字词并调用countStrings(words[i]);

public String convertItalics() {
    String toReturn = " ";
//***line below will never result in even number, since you are passing one "_", pass a whole word//***
    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;
}

答案 1 :(得分:0)

如果要替换Java中的字符,我建议使用“替换”方法 例如:

 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'));

这将基本上用“o”代替“i”。另外,如果你想比较java中的字符串你必须使用方法equals或equalsIgnoreCase而不是==,因为你正在比较字符数和正确的顺序而不是这些字符串的值

我希望这可以帮到你!

答案 2 :(得分:0)

你在做屏幕报废吗?有很多方法可以做到这一点。 REGEX,字符串操作,堆栈等。

这是一种简单的方法。

String code = "hello _my name is _chomez_";
code = code.replace("_", "<li>");

现在您已成功将其转换为:

hello <li>my name is <li>chomez<li>

现在只需要做交替的结束标记。

int n = code.indexOf("<li>", code.indexOf("<li>") + 1);
code = code.substring(0,n+1) + "/" + code.substring(n+1);

现在你有:

hello <li>my name is </li>chomez<li>

如果要处理的标记超过3个,只需运行一个循环,并将所有偶数位置标记替换为结束标记。算法将像,有标签,继续循环。如果这是第2,第4,第6 ......(偶数位置标签),请将其替换为</li>

答案 3 :(得分:0)

以下代码完全符合您的要求:

public String convertItalics() 
{      
    String[] tags = {"</i>", "<i>"};
    StringBuilder builder = new StringBuilder(line);

    int matchIndex = 0, counter = 0;        

    while((matchIndex = builder.indexOf("_", matchIndex)) > 0)
    {           
        counter++;              
        int length = builder.length();
        int endIndex = matchIndex + 1;

        if(endIndex > length ||  endIndex == 0) endIndex = length;

        builder.replace(matchIndex, endIndex, tags[counter % 2]);               
    }

    return builder.toString();
}


例如如果实例变量行等于"hello _my name_ is _chomez_ _l",那么输出将为:

hello <i>my name</i> is <i>chomez</i> <i>l



希望这可以帮助。祝你好运,玩得开心!

干杯,

高远