trim()方法不删除文本前面的空格?

时间:2014-04-30 14:55:41

标签: java string trim hashset stringbuffer

请查看以下代码

while (reader.hasNext()) 
          {
          JsonParser  _parser = new JsonParser();
          JsonElement jsonElement =  _parser.parse(reader);
          JsonObject jsonObject1 = jsonElement.getAsJsonObject();

              int totalNumberOfUniqueWords=0;

          //Add Title and Body Together to the list
          String titleAndBodyContainer = " My Name is something that you don't know. you know that anyway? My Name?";

              //Remove full stops and commas
              titleAndBodyContainer.trim();
          titleAndBodyContainer = titleAndBodyContainer.replaceAll("[^a-zA-Z'\\s]+", " ");
          titleAndBodyContainer = titleAndBodyContainer.toLowerCase();
              titleAndBodyContainer.trim();

              StringBuffer wordList = new StringBuffer("");

              //Removing Duplicate Words
              HashSet<String>noDup = new HashSet<String>();
              String[]titleAndBodyContainerArray = titleAndBodyContainer.split(" ");

              for(int i=0;i<titleAndBodyContainerArray.length;i++)
              {
                  if(!noDup.contains(titleAndBodyContainerArray[i].trim()))
                  {
                      wordList.append(titleAndBodyContainerArray[i].trim());
                      wordList.append(";");
                      noDup.add(titleAndBodyContainerArray[i].trim());
                      break;
                  }
              }

              System.out.println(wordList.toString());
              break;


              //index++;
          }

在所有时间中,输出为;。这只是意味着句子前面的空格不会被删除!如果我将titleAndBodyContainer替换为"My Name is something that you don't know. you know that anyway? My Name?",则没有输出,因为它在句子前面没有空格。这有什么不对?

1 个答案:

答案 0 :(得分:2)

titleAndBodyContainer.trim()不修剪原始字符串,但返回它的修剪版本。

尝试

String trimmedTitleAndBodyContainer = titleAndBodyContainer.trim();

然后处理结果。