oop-labs-collection/labs/5/Sentence.java

100 lines
2.6 KiB
Java
Raw Normal View History

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sentence {
private Word[] words;
private Symbol ending;
public Sentence(Word[] words, Symbol ending) {
this.words = words;
}
public Sentence(Word[] words) {
this.words = words;
}
public Sentence(String sentence) {
int totalSentenceLength = sentence.length();
this.ending = new Symbol(sentence.charAt(totalSentenceLength-1));
String[] rawWords = sentence.substring(0, totalSentenceLength-1)
.split("(?<=[,;:]?) ");
Word[] preparedWords = new Word[rawWords.length];
for (int i = 0; i < rawWords.length; i++) {
preparedWords[i] = new Word(rawWords[i]);
}
this.words = preparedWords;
}
public void addWord(Word newWord) {
Word[] newWordArray = new Word[1];
newWordArray[0] = newWord;
addWords(newWordArray);
}
public void addWords(Word[] newWords) {
int currentWordsAmount = this.words.length;
int newWordsAmount = newWords.length;
int totalLength = currentWordsAmount + newWordsAmount;
Word[] updatedWords = new Word[currentWordsAmount + newWordsAmount];
for (int i = 0; i < currentWordsAmount; i++) {
updatedWords[i] = this.words[i];
}
for (int i = 0; i < newWordsAmount; i++) {
updatedWords[currentWordsAmount+i] = newWords[i];
}
this.words = updatedWords;
}
public int index(Word w) {
int wordIndex = -1;
for (int i = 0; i < this.words.length; i++) {
if (this.words[i].equals(w)) {
wordIndex = i;
break;
}
}
return wordIndex;
}
public void removeWord(Word w) {
int deleteIndex = index(w);
removeWord(deleteIndex);
}
public void removeWord(int deleteIndex) {
// first pass, lookup
Word[] updatedArray = new Word[this.words.length-1];
for (int i = 0; i < deleteIndex; i++) {
updatedArray[i] = this.words[i];
}
for (int i = 0; i < this.words.length - deleteIndex - 2; i++) {
updatedArray[deleteIndex+i] = this.words[deleteIndex+i+1];
}
this.words = updatedArray;
}
public String toString() {
String result = "";
for (Word i : this.words) {
result += i.toString() + " ";
}
return result.substring(0, result.length()-1) + this.ending.toString();
//return result;
}
}