我想创建一个应用程序,它允许我在文本输入中输入名称并在故事中使用这些名称。
我会输入三个名为strGuide
,strHost1
和strHost2
的输入。在填写名称后,您会在onClick
事件中转到包含此示例的简短故事的新页面:
“你好,我是 strGuide 我今天将由 srtHost1 和 strHost2 陪同。今天我们走进大厦时,感受到您可以随时询问 strHost1 或 strHost2 。“
我希望strGuide
,strHost1
和strHost2
名称可以替换故事中的相同名称。这是一个简短的例子。实际上,故事将是整个巡演的剧本。还有三个游览,所以我想从story1,story2或story3中选择。我已经找到了答案,但我找不到我要找的东西。
答案 0 :(得分:2)
使用replace()
String
演示使用String.replace()的示例,这不包括您的整个故事!
public class Test {
public static void main(String[] args) {
String story = "Hello, I am strHost and I will be accompanied today by strHost1 and strHost2. As we walk through the mansion today, feel free to ask strHost1 or strHost2 any questions you may have.";
String str = story.replaceAll("strHost1", "stringhost1");
str = str.replaceAll("strHost2", "stringhost2");
str = str.replaceAll("strHost", "stringhost");
System.out.println(str);
}
}
查看String
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
<强>更新 java docs:
replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement
另一个例子,
public static void main(String[] args) {
String story = "Hello, I am strHost and I will be accompanied today by someguy1 and anotherguy2. As we walk through the mansion today, feel free to ask someguy1 or anotherguy2 any questions you may have.";
String str = story.replaceAll("someguy1", "someguy1peter");
str = str.replaceAll("anotherguy2", "anotherguy2john");
str = str.replaceAll("strHost", "stringhost");
System.out.println(str);
}
输出:
Hello, I am stringhost and I will be accompanied today by someguy1peter and anotherguy2john. As we walk through the mansion today, feel free to ask someguy1peter or anotherguy2john any questions you may have.