0

How do i count space between two string in java
for ex. String s = "This is my car";

i have to count number of space between this and is , is and my, and my and car.

4
Contributors
7
Replies
9
Views
6 Years
Discussion Span
Last Post by ztini
0

there is more than one space between each word this 3Space is 2Sapce my 1Space car

0

How do i count space between two string in java
for ex. String s = "This is my car";

i have to count number of space between this and is , is and my, and my and car.

there is more than one space between each word this 3Space is 2Sapce my 1Space car

0

you could first get the length of the whole string and use a for loop to to go down the word and if charAt(i) == " " then increase a count and return count.

0

or you could assume that, since stuff like this can in a lot of ways be usefull, it has been implemented in Java already.
just go and take a look at what StringTokenizer is all about.
I'm quite sure it 'll help you do everything you want (except for making a cup of coffee when it's done :P )

0
public class SpaceCount {
	public static void main(String[] args) {
		String s = "This is my car.";
		int count = 0;
		
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ' ') count++;
		}
		
		System.out.println(count);
	}
}

Edited by ztini: n/a

0
public class SpaceCount {
	public static void main(String[] args) {		
		String line = "This is my car.";
		String[] spaces = line.split(" ");
		System.out.println(spaces.length - 1);
	}
}

Both examples are O(n) efficient; this second example is just cleaner imo.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.