how can I know empty space and first not empty char of string sentence
Hello
My English ability is very poor sorry
I get a string from database
================
first blah
two empty space blah
five space bar pushed blah
==================
I want to know space count of sentence
first is 0: sencond is : 2 , last is : 5
and I want to know first and second character of sentence (not space bar)
first is : fi , secode is : tw, last is : fi
plz help me
Read through the documentation of the String class. Examine the methods split, trim and substring which, between them, will do what you want.
String[] lines =
{
"first blah",
"two empty space blah",
"five space bar pushed blah",
};
for (String line : lines)
{
int countOfSpaces = line.replaceAll("[^ ]","").length();
System.out.println(countOfSpaces + "\t" + line.charAt(0) + "\t" + line.charAt(1) + "\t" + line.substring(0,2) + "\t" + line);
}
Message was edited by:
sabre150
It's hard to say what the data should look like, but it looks like the OP has this data in mind:
String[] lines = {
"blah", // zero spaces
" blah",// two spaces
"blah", // five spaces
};
But it's hard to tell if e.g.
String[] lines = {
"blah",
" blah string with spaces"
};
also is valid data.
Kaj
> > It's hard to say what the data should look like,
> but
> > it looks like the OP has this data in mind:
>
> Ahh! I obviously got the wrong end of the stick.
>
> And having read it again I still can't see what the
> OP wants.
>
> Message was edited by:
> sabre150
I read it again, and now I'm even more confused, but I think I found it. The OP couldn't post formatted text. Quoting the OP gives:
================
first blah
two empty space blah
five space bar pushed blah
===============
So the task is probably to count number of spaces in the beginning of each line, and then list the two first characters of each line (excluding the spaces)
Kaj
>
> So the task is probably to count number of spaces in
> the beginning of each line, and then list the two
> first characters of each line (excluding the spaces)
>
I think you are right Kaj. Since this is then obviously homework the OP will probably not be able to use regex. :-(
So I can post this without worrying that the OP will submit it
Pattern p = Pattern.compile("( +)(..).*");
String[] lines =
{
" bxlah",
" bylah",
"bzlah",
};
for (String line : lines)
{
Matcher m = p.matcher(line);
if (m.matches())
System.out.println(m.group(1).length() + "\t" + m.group(2) + "\t[" + line + "]");
}
Message was edited by:
sabre150