【发布时间】:2019-03-03 01:11:22
【问题描述】:
我面临一个小挑战,这就是我一直在尝试做的事情。
假设我有这两个变量
String word1 ="hello! hello!! %can you hear me%? Yes I can.";
And then this one
String word2 ="*Java is awesome* Do you % agree % with us?";
我希望能够检查一个变量是否包含一个以我正在使用和替换的特定符号(如 % 和 *)开头和结尾的单词;带有“1”(一个)。这是我尝试过的。
StringTokenizer st = new StringTokenizer(word1);
while(st.hasMoreTokens()){
String block = st.nextToken();
if( (block.startsWith("%") && block.endsWith("%") ||(block.startsWith("*") && block.endsWith("*")){
word1.replace (block,"1");
}
}
//output
'hello!hello!!%canyouhearme%?YesIcan."
//expected
"hello! hello!! 1? Yes I can.";
它刚刚修剪它。我想这是因为使用的分隔符是空格,并且最后一个 % 以 %?它将它作为一个单独的块读取。
When I tried the same for word2
I got "1Doyou%agree%withus?"
//expected
"1 Do you 1 with us?"
假设我还有另一个词,比如
String word3 ="%*hello*% friends";
I want to be able to produce
//output
"1friends"
//expected
"11 friends"
Since it has 4-symbols
任何帮助将不胜感激,只是提高我的 Java 技能。谢谢。
【问题讨论】:
-
我认为您不需要令牌。您可以使用
charAt()来检查您的符号并使用replaceAll()将其替换为 1 -
%*hello*%如何翻译成数字11,这4个符号是从哪里来的? -
@surendrapanday 和哪个计数系统是 4?
hello有 5 个字符...不确定*消失在哪里,怎么变成 11? -
@surendrapanday 但这应该导致“1”,而不是“11”,因为他从未说过不应该替换“%1%”之类的东西,而是在现有的后面附加另一个“1” .
-
好吧,他指的是特殊字符的特殊符号。
%**%是四个符号,而不是应该说特殊字符,这就是他的错误。
标签: java