I want to find how many words there are in a string but ignore the similar words in it.
For example the main method should return 8 insetad of 9.
I want it to be a method which takes one parameter s of type String and returns an int value. And im only allowed to use the bacics,so no HashMaps, ArrayLists, only charAt, length, or substring and using loops and if statemens are allowed.
public static void main(String[] args) {
countUniqueWords("A long long time ago, I can still remember");
public static int countUniqueWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt ;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}
```
CodePudding user response:
Don't force yourself to limited options, and learn the Streaming API. Your question is as simple as:
public static long countUniqueWords(String str) {
var str2 = str.replaceAll("[^a-zA-Z0-9 ]", "").replaceAll(" ", " ");
return Arrays.stream(str2.split(" "))
.distinct()
.count();
}
- [Optional step] Get get rid of all non alphanumeric chars
- Split the string per empty slot
- Remove duplicates
- Add them together
CodePudding user response:
To ignore same words in a string, you can use a combination of the split and distinct methods from the Java Stream API.
// Define the input string
String input = "This is a test string with some repeating words";
// Split the string into an array of words
String[] words = input.split("\\s ");
// Use the distinct method to remove duplicate words from the array
String[] distinctWords = Arrays.stream(words).distinct().toArray(String[]::new);
// Print the distinct words
System.out.println(Arrays.toString(distinctWords));
CodePudding user response:
Try this:
public static int countUniqueWords(String words) {
// Add all the words to a list
List<String> array = new ArrayList<>();
Scanner in = new Scanner(words);
while (in.hasNext()) {
String s = in.next();
array.add(s);
}
// Save per word the amount of duplicates
HashMap<String, Integer> listOfWords = new HashMap<>();
Iterator<String> itr = array.iterator();
while (itr.hasNext()) {
String next = itr.next();
String prev = listOfWords.getOrDefault(next, 0);
listOfWords.put(next, prev 1);
}
// Grab the size of all known words
return listOfWords.size();
}
public static void main(String args[]) {
int count = countUniqueWords("A long long time ago, I can still remember");
System.out.println("The number of unique words: " count);
}