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

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

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.

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 )

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 5 Years Ago by ztini: n/a

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.