Reputation: 13
I'm trying to tokenize letters of a string array, versus the string type.
I used .split()
for converting a string into an array that consisted of each word in the array, but I'm having trouble finding a similar method to tokenize letters in the array.
I tried looking online for a method or tool to use but I haven't had any luck with regard to string arrays. Maybe something similar to substring?
If someone could point me in the right direction it would be appreciated.
Here's what I have:
// i variables run through rows and j variables run through each word in the string array.
// tokens is the string array
for(int i = 0; i < tokens.length; i ++){
for(int j = 0; j < tokens[i].length; j++)
...
}
Is there a method with regards to arrays to compute the length of each word within each row of the array?
Upvotes: 0
Views: 53
Reputation: 54168
Consider size
is the length you want for each part, you have to substring from a index
to index+size
and do this iterating over the string until you reach the end which will be given by the length of string minus the size
It's better to use a List
rather than an array
because it's easier to add elements, sure you can compute the number of split you'll get, but that's another way
Version using IntStream
and Streams
:
String str = new Scanner(System.in).nextLine();
int size = 2;
List<String> res = IntStream.range(0, str.length() - size + 1)
.mapToObj(i -> str.substring(i, i + size))
.collect(Collectors.toList());
System.out.println(res); // [he, el, ll, lo]
Version using basic for-loop
:
String str = new Scanner(System.in).nextLine();
int size = 3;
List<String> res = new ArrayList<>();
for (int i = 0; i < str.length() - size + 1; i++) {
res.add(str.substring(i, i + size));
}
System.out.println(res); // [hel, ell, llo]
Upvotes: 2