如何简单地获取java中字符串前缀上所有出现的字符?
我有一个像这样的字符串:'0010'
如何获取该示例字符串的前两个零。这里的规则是,我有一个保存字符的变量。然后我需要查看字符串,如果字符串的第一个字符与变量值相同。我需要保留它,然后如果第二个字符串再次匹配,则将其连接起来,依此类推。如果字符串的第一个字符与变量值不匹配,则它将不会存储也不会再次查找前一个字符。
虽然我已经有了解决方案,但我使用了大约 10 行代码来做到这一点。
这是我的代码:
String start = "0001";
String concatVal = "";
char prefix = '0';
for(int i = 0; i < start.length(); i++){
if(start.charAt(i) == prefix){
concatVal += prefix;
} else {
break;
}
}
System.out.println(concatVal);
//Output
000
如果有更简单的方法来实现此目的,请告诉我。谢谢
I have a string like this: '0010'
How can I get the first two zero on that sample string. The rules here is that, I have a variable which hold a character. Then I need to look on the string, if the first character of the string is same with the variable value. I need to keep it and then if the second string matches again, concatenate it and so on. If the first character of the string is not matched with the variable value then it will not store and not look again on the preceding character.
Though I have already solution but I used about 10 lines of codes to do this.
Here is my code:
String start = "0001";
String concatVal = "";
char prefix = '0';
for(int i = 0; i < start.length(); i++){
if(start.charAt(i) == prefix){
concatVal += prefix;
} else {
break;
}
}
System.out.println(concatVal);
//Output
000
If there is a more simple way to achieve this, please let me know. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在不逐字符构建结果字符串的情况下完成此操作。相反,查找可能匹配的长度,然后从原始字符串中剪切。
You may do it without building the result string char-by-char. Instead look for the length of the possible match and then cut from the original string.
看起来不错,一个可能的改变是
Looks pretty good, one possible change would be
你的代码已经很简单了。英文描述并不短,所以不用担心。通过一点点重写,您会得到:
这个定义只有四行实际长度:
与您的描述相比,这确实很短。
Your code is already very simple. The English description isn't much shorter, so don't worry. With a little bit of rewriting you get:
This definition is only four real lines long:
Compared to your description, this is really short.
您只需从原始字符串中提取结果即可。
You could just extract the result from the original string.