[英]How to modify this String in Java?
Suppose I am having two Strings as follows : 假设我有两个String,如下所示:
String name = "EXAMPLE_MODEL_1";
String actionName = "ListModels";
I want resulting string as Follows : 我想要结果字符串如下:
String result = "ExampleModel1ListModels";
I tried the Follwoing code : 我尝试了Follwoing代码:
String result = name.toLowerCase().replaceAll("_", "");
result = result.concat(actioName);
And I am getting the result value as "examplemodel1ListModels". 我得到的结果值是“ examplemodel1ListModels”。 But the exepected one is "ExampleModel1ListModels".
但可以预期的是“ ExampleModel1ListModels”。
The name
string needs to have the underscores replaced -- you've done that. name
字符串需要替换下划线-您已完成。 Before you do that, you need to convert it to title case . 在此之前,您需要将其转换为title case 。
After that, simply concatenate the two strings. 之后,只需连接两个字符串即可。
You are using toLowerCase()
method so you are getting result like that. 您正在使用
toLowerCase()
方法,因此会得到类似的结果。 Don't use this function. 不要使用此功能。
Combine your partial solution, with the function described here: 将部分解决方案与此处描述的功能结合起来:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)? 将Java字符串从所有大写字母(用下划线分隔的单词)转换为CamelCase(无单词分隔符)的最简单方法是什么?
使用Apache的WordUtil.Capitalize
方法。
使用番石榴的CaseFormat
String result = LOWER_UNDERSCORE.to(UPPER_CAMEL, "EXAMPLE_MODEL_1") + "ListModels";
Apache commons-lang has utility classes that can help you. Apache commons-lang的实用程序类可以为您提供帮助。 Below is my idea
以下是我的主意
Try to use the following code (I'm editing and paste the full code) 尝试使用以下代码(我正在编辑并粘贴完整代码)
import java.io.IOException;
public class StringTest{
public static void main(String[] arg) throws IOException{
String name = "EXAMPLE_MODEL_1"; String actionName = "ListModels";
String result = toProperCase(name.toLowerCase().replaceAll("_", " "))+actionName;
result= result.replaceAll(" ","");
System.out.println(result);
}
public static String toProperCase(String theString) throws java.io.IOException{
java.io.StringReader in = new java.io.StringReader(theString.toLowerCase());
boolean precededBySpace = true;
StringBuffer properCase = new StringBuffer();
while(true) {
int i = in.read();
if (i == -1) break;
char c = (char)i;
if (c == ' ' || c == '"' || c == '(' || c == '.' || c == '/' || c == '\\' || c == ',') {
properCase.append(c);
precededBySpace = true;
} else {
if (precededBySpace) {
properCase.append(Character.toUpperCase(c));
} else {
properCase.append(c);
}
precededBySpace = false;
}
}
return properCase.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.