Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by forester on 08.11.15.
- */
- public class Run {
- public static void main(String[] args) {
- String oneWord = "hello";
- String twoWordsSpace = "hello world";
- String twoWordsUnderscore = "hello_world";
- String allCases = "__ hello _ from demo tests123 __ ";
- countWordLengths(oneWord);
- System.out.println();
- countWordLengths(twoWordsSpace);
- System.out.println();
- countWordLengths(twoWordsUnderscore);
- System.out.println();
- countWordLengths(allCases);
- }
- public static void countWordLengths(String str) {
- if (str.isEmpty())
- return;
- String word = "" + str.charAt(0);
- boolean prevCharIsSpace = isSpaceCharacter(str.charAt(0));
- int counter = prevCharIsSpace ? 0 : 1;
- for (int i = 1; i < str.length(); i++) {
- boolean curCharIsSpace = isSpaceCharacter(str.charAt(i));
- if (i == str.length() - 1) {
- counter = curCharIsSpace ? counter : counter + 1;
- word += curCharIsSpace ? "" : "" + str.charAt(i);
- if (counter != 0) {
- System.out.println(word + ":" + counter);
- }
- }
- if (prevCharIsSpace && curCharIsSpace) {
- continue;
- } else if ((!prevCharIsSpace && !curCharIsSpace) || (curCharIsSpace && !prevCharIsSpace)) {
- if (!curCharIsSpace) {
- counter++;
- word += str.charAt(i);
- }
- prevCharIsSpace = curCharIsSpace;
- } else if ((!prevCharIsSpace && curCharIsSpace) || (!curCharIsSpace && prevCharIsSpace)) {
- if (counter != 0) {
- System.out.println(word + ":" + counter);
- }
- counter = curCharIsSpace ? 0 : 1;
- word = curCharIsSpace ? "" : str.charAt(i) + "";
- prevCharIsSpace = curCharIsSpace;
- }
- }
- }
- public static boolean isSpaceCharacter(char c)
- {
- for (int i = 0; i < SPACE_CHARS.length; i++) {
- if (SPACE_CHARS[i] == c)
- return true;
- }
- return false;
- }
- private static final char SPACE_CHARS[] = {' ', '_'};
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement