如何摆脱输入字符串
How to get rid of enter in String
当我尝试对我的字符串进行一些操作时,我的 tMap 出现问题。我有一个 Ad_Set_Name 的 csv,在某些行中单元格中有更多行。我使用以下内容:
row4.Ad_Set_Name.contains(" ") ? row4.Ad_Set_Name.substring(0,row4.Ad_Set_Name.indexOf(" ")) : row4.Ad_Set_Name
row4.Ad_Set_Name.contains("\"") ? row4.Ad_Set_Name.substring(row4.Ad_Set_Name.indexOf("\"")+1,row4.Ad_Set_Name.lastIndexOf("\"")) : "null"
我说 Ad_Set_Name "Other vc_7days"。所以在这种情况下,第一行会给我 "Other",第二行会给我 "null"。 Ad_Set_Name = "Other vc_7days "something" 3rd" 第一行将 return "Other" 和第二行 "something"。但是当我有 Ad_Set_Name=
“其他
东西” 我有一个索引错误,例如:"StringIndexOutOfBoundsException: String index out of range: -1" 知道为什么吗? 非常感谢!
错误日志是:
Exception in component tMap_1 (facebook_campaigns_amazon_us)
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at mava2.facebook_campaigns_amazon_us_0_1.facebook_campaigns_amazon_us.tFileInputDelimited_2Process(facebook_campaigns_amazon_us.java:4649)
at mava2.facebook_campaigns_amazon_us_0_1.facebook_campaigns_amazon_us.tWaitForFile_1Process(facebook_campaigns_amazon_us.java:2322)
at mava2.facebook_campaigns_amazon_us_0_1.facebook_campaigns_amazon_us.tMysqlConnection_1Process(facebook_campaigns_amazon_us.java:856)
at mava2.facebook_campaigns_amazon_us_0_1.facebook_campaigns_amazon_us.runJobInTOS(facebook_campaigns_amazon_us.java:5905)
at mava2.facebook_campaigns_amazon_us_0_1.facebook_campaigns_amazon_us.main(facebook_campaigns_amazon_us.java:5575)
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
告诉我们有一个非空字符串不包含您要查找的字符。
在您的情况下,当存在 </code>(空格)或 <code>"
.
使用 Java 复制它看起来像这样:
String test = "\"Other \n\nthings\"";
test = test.contains(" ") ? test.substring(0, test.indexOf(" ")) : test;
System.out.println(test); // "Other
System.out.println(test.contains("\"") ?
test.substring(test.indexOf("\"")+1,test.lastIndexOf("\"")) : "null"); // error!
你收到一个错误,因为当你第二次验证运行时,字符串是 "Other
,这意味着
test.contains("\"") ? test.substring(test.indexOf("\"")+1,test.lastIndexOf("\"")) : "null"
实际上解析为
test.contains("\"") ? test.substring(0+1, 0) : "null"
并且由javadoc
指定IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
在您的例子中,beginIndex 为 1,endIndex 为 0,这就是抛出 StringIndexOutOfBoundsException
的原因。
为了防止抛出该错误,而不是使用
row4.Ad_Set_Name.contains("\"")
使用
row4.Ad_Set_Name.indexOf('"', 2) != -1
这将确保您的字符串至少出现 2 次字符 "
。
我解决了这个问题。在 tFileInputDelimited 元素中,我没有检查 CSV 选项。因为 Talend 读取带有“”的多行单元格,我必须在“\”上设置转义字符。