-2

I need to capitalize first character of a sentence where sentence ends with a period. ( it could be multiple periods too) OR !

 String result = "";
 Scanner scanner = new Scanner(content);
 scanner.useDelimiter("(?<=(\\.+))|(?<=!)");
 while (scanner.hasNext()) {
     String line = scanner.next();
     String line1 = line.substring(0, 1).toUpperCase() + line.substring(1);
     result = result + line1;
 }

When i do this , the whitespace new line character is present at the 0 index and the program doesn't capitalize the letter.

Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
Zebra
  • 139
  • 2
  • 10

1 Answers1

0

Trim the line:

String line = scanner.next().trim();

Zach
  • 11
  • 2
  • Thanks ! It is close but i need to retain the new line character as well when i write back. – Zebra Nov 16 '17 at 15:42
  • result = line1 + System.lineSeparator(); – Zach Nov 16 '17 at 15:48
  • Thanks . It works. Do you know when i use scanner.useDelimiter("(?<=(\\.+)) this why it creates multiple splits for a sentence like " come soon ... Please come back" . I would expect it to break into two splits but it break each period into a new split. – Zebra Nov 16 '17 at 16:15
  • What kind of delimiter do you have in mind? Delineate around one exclamation mark or one or more periods? – Zach Nov 16 '17 at 16:25
  • Yes, one or more period or exclamation marks . I thought regex (\\.+) should take care of it. – Zebra Nov 16 '17 at 17:00
  • I do not understand the use of the zero-width positive look-behind. How about “\\s*[!.]+\\s*” – Zach Nov 16 '17 at 17:08
  • if i don't use look behind , i don't get to retain the delimiters when i write back my string to a file. – Zebra Nov 16 '17 at 17:17
  • So add them when you do the write back. – Zach Nov 16 '17 at 17:20
  • how would i know what delimiter was used to separate the fields ? – Zebra Nov 16 '17 at 17:21
  • Oh, you want to retain the diameters and use them as delimiters? "?<=[!.]+” maybe. – Zach Nov 16 '17 at 17:25
  • Yes, i want to retain the delimiters and also use them as delimiters to split the sentences. I need to perform some operations when i split them. – Zebra Nov 16 '17 at 17:45
  • for e.g. This is coming .... because you said it will ! then lets go... done. I should expect on splitting using the delimiter and retaining it => This is coming .... 2) because you said it will ! 3) then lets go .... 4) done. – Zebra Nov 16 '17 at 17:46
  • Ok, so the problem is that the split happens left to right, and applies as soon as the conditions are met. You have to tighten the conditions. This works: "(?<=[!.]+)(?![!.])" At least as a string split. Not sure if real-time input to a scanner will behave the same. – Zach Nov 16 '17 at 18:03