简体   繁体   English

要替换字符串数组中的空白

[英]Want to replace WhiteSpace from array of String

private static final String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
private static final String SQL_CREATE = "CREATE TABLE ${table}(${keys} VARCHAR(20) NOT NULL)";
private static final String TABLE_REGEX = "\\$\\{table\\}";
private static final String KEYS_REGEX = "\\$\\{keys\\}";
private static final String VALUES_REGEX = "\\$\\{values\\}";

String[] headerRow = csvReader.readNext();//getting(Machine Name , Value)
String[] stripedHeaderRow = StringUtils.stripAll(headerRow);

String query2 = SQL_CREATE.replaceFirst(TABLE_REGEX, tableName);
query2 = query2.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, " VARCHAR(20) NOT NULL,"));

Result: 结果:

"Machine Name, Value"

Expected result: 预期结果:

"MachineName , Value"

You can do it with regular expression in JAVA. 您可以在JAVA中使用正则表达式来实现。 for example: 例如:

String a = "Hello    World!!";
 a = a.replaceAll("\\s","");

Now the value of a = "HelloWorld!!" 现在, a = "HelloWorld!!"

Assuming your array is in temp variable, 假设您的数组位于temp变量中,

Here is how you can get all spaces trimmed between every string. 这是您如何在每个字符串之间修剪所有空格的方法。

String[] temp = {"My Name Is", "And so Far", "All good", "Really?", 
                             "That makes no sense to me", "Oh! Somehthing Like This"};
Stream<String> stream = Arrays.stream(temp);
temp = stream.map(str -> str.replaceAll("\\s",""))
         .toArray(size -> new String[size]);

Now if printing it, it would give this.. 现在,如果将其打印出来,它将得到此效果。

for(String st : temp)
        System.out.println(st);

Output:- 输出:-

MyNameIs
AndsoFar
Allgood
Really?
Thatmakesnosensetome
Oh!SomehthingLikeThis

I created arrayList to modify the array of String contents, 我创建了arrayList来修改String内容的数组,

List<String> al = new ArrayList<String>();
for (String element: headerRow) 
     { 
         al.add(element.replace(' ', '_')); 

    }
String[] stripedHeaderRow = al.toArray(new String[al.size()]);//Creating new array of String

//This will fulfill my result. //这将实现我的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM