返回一个新字符串,其中包含原始字符串的所有字符,每个字符之间有下划线

问题描述 投票:0回答:1

我正在尝试创建一个方法,其中返回 currentString 并在每个字符中间带有下划线。例如,如果当前字符串是:“hi there”,则输出字符串将为“h_i_t_h_e_r_e”,开头或结尾没有下划线。我知道这可以使用 regex 和 ReplaceAll 来完成,但我正在尝试使用 for 循环来完成此操作

我当前的代码如下所示:

 public String spacedWord()
    {
            String spacedString = "";
            for (int i = 0; i<currentString.length(); i++)
            {
                spacedString = spacedString+currentString.charAt(i)+"_";
            
            }
            return spacedString;
            
    }

如果当前字符串是“嘿那里”,我的代码将返回“h_e_y_ t_h_e_r_e”,末尾带有下划线。

代码正确返回,每个字符之间都有下划线,但我不确定如何确保下划线不会出现在字符串末尾。

如有任何帮助,我们将不胜感激!

java string for-loop methods charat
1个回答
0
投票

“-1”技巧。

String spacedString = "";
String currentString= "Hello Peaple";
for (int i = 0; i<currentString.length()-1; i++)
{
    spacedString = spacedString+currentString.charAt(i)+"_";
}
spacedString = spacedString+currentString.charAt(currentString.length()-1);
return spacedString;
© www.soinside.com 2019 - 2024. All rights reserved.