【问题标题】:How to replace a point ('.') in a string, with the word before the point?如何用点之前的单词替换字符串中的点('.')?
【发布时间】:2015-11-13 21:56:26
【问题描述】:

如果我们有

String x="Hello.World";

我希望将 '.' 替换为 "Hello",例如:"HelloHelloWorld"

问题是,如果我有:

String Y="Hello.beautiful.world.how.are.you;"

答案必须是"HelloHellobeautifulbeautifulworldworldhowhowareareyouyou"

请记住,我不能使用数组。

【问题讨论】:

  • 遍历字符串。开始构建“最后看到的单词”字符串,每当你看到.,吐出那个“最后看到的单词”,然后重新开始构建。
  • 你有什么尝试吗?
  • 您是否尝试将点转换为它前面的字符串?
  • 为什么会有问题?
  • 为什么你的例子中有两个you(后面没有.)?

标签: java string replace character


【解决方案1】:

我认为您可以使用正则表达式替换来实现这一点。在正则表达式中,您可以使用所谓的“捕获组”。您将一个单词加上一个点与您的正则表达式匹配,然后将其替换为匹配单词的两倍。

// Match any number of word characters plus a dot
Pattern regex = Pattern.compile("(\\w*)\\.");

Matcher regexMatcher = regex.matcher(text);

// $1 is the matched word, so $1$1 is just two times that word.
resultText = regexMatcher.replaceAll("$1$1");

请注意,我没有尝试过,因为设置 Java 环境等可能需要半个小时。但我非常有信心它可以工作。

【讨论】:

  • 如果他不能使用数组,我会认为正则表达式也是不可能的。
  • 我知道有这种可能性,但为了完整起见,我还是想提一下。要么他可以使用它们,那么这应该是一个很好的答案,否则,他可以更新问题并忽略它。
【解决方案2】:

把这个问题想象成一个指针问题。您需要保持一个正在运行的pointer 指向您查看的最后一个位置(我的代码中的firstIndex),以及一个指向您当前位置的指针(我的代码中的nextIndex)。在这些地方之间的任何地方调用subString()(在第一次出现后将1添加到firstIndex,因为我们不需要捕获“。”),将它两次附加到一个新字符串,然后更改您的指针。可能有一个更优雅的解决方案,但这可以完成工作:

    String Y="Hello.beautiful.world.how.are.you";
    int firstIndex=0;
    int nextIndex=Y.indexOf(".",firstIndex);

    String newString = "";
    while(nextIndex != -1){
        newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex);
        newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex);
        firstIndex=nextIndex;
        nextIndex=Y.indexOf(".", nextIndex+1);
    }

    System.out.println(newString);

输出:

HelloHellobeautifulbeautifulworldworldhowhowareare

【讨论】:

  • LGTM,但您应该(可能)将其更改为在最后一个点之后附加字符串。但是,这个问题并不是很具体。
【解决方案3】:

这就是我所拥有的:

public String meowDot(String meow){
    int length = meow.length();
    String beforeDot = "";
    String afterDot;
    char character;
    for(int i=0; i < length; i++){
        character = meow.charAt(i);
        if (i < largo - 1 && character == '.'){
            beforeDot += meow.substring(0, i) + meow.substring(0, i);
            afterDot = meow.substring(i, length);
            meow = afterDot;
        } else if(i == length - 1 && character != '.'){
            afterDot += meow + meow;
        }          
    }
    return beforeDot;
}

【讨论】:

  • 您应该在原始帖子中发布您的尝试。
  • 这个算法有个小问题。您将 meow 更改为点之后的内容,但是您没有重置变量 i,即您继续在错误的位置。
  • @JackmeriusTacktheritrix 用户可以回答他们自己的问题,即使它不起作用。如果其他答案更好,将被投票赞成
  • @AlastairMcCormack 我意识到这一点,但我认为这是他发布了他最初的错误尝试,而不是他说他解决了它并发布了答案。
  • @JackmeriusTacktheritrix 非常正确 :) 这是一个结构非常糟糕的问题和答案,对其他人几乎没有价值。我已经投票关闭。
猜你喜欢
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2013-12-27
  • 2015-07-03
  • 1970-01-01
相关资源
最近更新 更多