首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在替换短语中的字符串时遇到问题

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

Stack Overflow用户
提问于 2014-12-13 00:31:25
回答 4查看 1.3K关注 0票数 1

我在替换短语中的某些字符串时遇到了问题。我必须将"_“替换为和"< / I>”交替。到目前为止我的代码如下:

代码语言:javascript
运行
复制
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_“这样的短语,它不会替换任何"_”。任何帮助都将不胜感激。谢谢!

编辑:感谢那些留下评论的人,我的课程快结束了,所以我会在有电脑使用和有时间的时候再来看看,谢谢大家!

EN

Stack Overflow用户

发布于 2014-12-13 00:41:39

如果你想替换Java中的字符,我建议使用" replace“方法,例如:

代码语言:javascript
运行
复制
 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而不是==方法,因为您要比较的是字符的数量和正确的顺序,而不是这些字符串的值。

我希望这能对你有所帮助!

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27447972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档