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.

Recommended Answers

All 7 Replies

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 )

Member Avatar for ztini
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);
	}
}

Looks good to me :) congrats

Member Avatar for ztini
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.