Counting Characters in a string
HI all!
I am new working with java and i have an application where I have to count specific characters in a string e.g. 'a','.','H','4' and so on! I found an entry in the forum with this script:
String text = "Hello World!";
int count = 0;
for (int x = 0; x < text.length(); x++)
if (text.charAt(x) == 'l')
count++;
This Script count all the 'I', but I could not get CharAt to count different characters at once!
Is there a way?
Thx for your help!
LeBite
String text = "Hello World!";
int countl = 0;
int counto = 0;
for (int x = 0; x < text.length(); x++)
if (text.charAt(x) == 'l') countl++;
if (text.charAt(x) == 'o') counto++;
[/code[
Similar Messages
-
How to count number of repeated characters in a String
I have a String.... 10022002202222.
I need to know how many 2's are there in the string... here the string contains eight 2's..
Thanks in advance..it is workingYes, but... attention to surprises...
SQL> var v1 varchar2(1000);
SQL> exec :v1 := 'How to count the number of occurences of a characters in a string';
PL/SQL procedure successfully completed.
SQL> select length(:v1) - length(replace(:v1,'c')) from dual;
LENGTH(:V1)-LENGTH(REPLACE(:V1,'C'))
6
SQL> exec :v1 := 'cccccc';
PL/SQL procedure successfully completed.
SQL> select length(:v1) - length(replace(:v1,'c')) from dual;
LENGTH(:V1)-LENGTH(REPLACE(:V1,'C'))
SQL> select length(:v1) - nvl(length(replace(:v1,'c')),0) from dual;
LENGTH(:V1)-NVL(LENGTH(REPLACE(:V1,'C')),0)
6
SQL> -
Method to count number of characters in a string?
hi.
i'm trying to write some script that will count the number of characters in a string passed into a constructor and then compare it against another value to check whether the string passed in is valid.
something like this
public class Stringcheck
public static int maxStringLength;
public static double minSize;
public static boolean testStringLength(String x)
// Insert method for counting number of chars in String x and name as 'int numberOfChars
if(number of Chars <= maxStringLength )
return true;
else
return false;
can someone help me with writing this script.
Thanks
Richard.ummm, you dont need anything fancy. try:
String test = "this is the test string";
int length = test.length(); -
Hie every one! I need help. I have written a program that ask the user to enter string, at the mmont it counts number of words, number of vowel , number of consonts.
Problem i am trying to solve is (1) when it counts characters i want to avoid counting numbers and things like ?;'".
(2) how do word frequency and word occurrence
this is what i have done and the rest is of the code i have left them
//I want this program to throw exception if the user enters numbers
String str;
System.out.print("Enter a String: ");
str = sc.nextLine();
for (int j=0; j<str.length();j++)
for (int i=0; i<vowles.length;i++)
ch = str.charAt(j);
if(ch==vowles)
total++;
if(str.charAt(j)== ' ')
word++;
chcount = str.length() - word;
System.out.println("Number of words =" + (word+1));
System.out.println();
System.out.println("number of vowels is =" + total);
System.out.println("Number of characters =" + (str.length() - word));
int cons = chcount - total;
System.out.println("number of conconast =" + cons);Take a look at the Character and String classes. They have the methods you require.
Look at these:
Character.isLetter('A');
Character.isDigit('A');Also if you want to check if a word is repeating then you could keep all your inputs in an array and you could check through each element (iterate) against the latest input using the equals mehtod.
See here for more info.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Character.html
http://home.cogeco.ca/~ve3ll/jatutor7.htm
http://www.devdaily.com/blog/Content/2/8/178/
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html
Come back if you get stuck! -
Count of characters in a string
Hi all,
Is there any way to find the repeating characters in the string like 'L' in the example Hello ..
Thanks in advance,
Nalla !
Message was edited by: Nalla
Nalla (Nallasivam)test@ORA10G>
test@ORA10G> with t as (
2 select 'hello' as str from dual union all
3 select 'abracadabra' from dual union all
4 select 'the quick brown fox jumps over the lazy dog' from dual union all
5 select 'abcdefghijklmnopqrstuvwxyz' from dual union all
6 select 'facetious' from dual)
7 --
8 select
9 str
10 from t
11 where (
12 length(str) - length(replace(lower(str),'a')) > 1 or
13 length(str) - length(replace(lower(str),'b')) > 1 or
14 length(str) - length(replace(lower(str),'c')) > 1 or
15 length(str) - length(replace(lower(str),'d')) > 1 or
16 length(str) - length(replace(lower(str),'e')) > 1 or
17 length(str) - length(replace(lower(str),'f')) > 1 or
18 length(str) - length(replace(lower(str),'g')) > 1 or
19 length(str) - length(replace(lower(str),'h')) > 1 or
20 length(str) - length(replace(lower(str),'i')) > 1 or
21 length(str) - length(replace(lower(str),'j')) > 1 or
22 length(str) - length(replace(lower(str),'k')) > 1 or
23 length(str) - length(replace(lower(str),'l')) > 1 or
24 length(str) - length(replace(lower(str),'m')) > 1 or
25 length(str) - length(replace(lower(str),'n')) > 1 or
26 length(str) - length(replace(lower(str),'o')) > 1 or
27 length(str) - length(replace(lower(str),'p')) > 1 or
28 length(str) - length(replace(lower(str),'q')) > 1 or
29 length(str) - length(replace(lower(str),'r')) > 1 or
30 length(str) - length(replace(lower(str),'s')) > 1 or
31 length(str) - length(replace(lower(str),'t')) > 1 or
32 length(str) - length(replace(lower(str),'u')) > 1 or
33 length(str) - length(replace(lower(str),'v')) > 1 or
34 length(str) - length(replace(lower(str),'w')) > 1 or
35 length(str) - length(replace(lower(str),'x')) > 1 or
36 length(str) - length(replace(lower(str),'y')) > 1 or
37 length(str) - length(replace(lower(str),'z')) > 1
38 );
STR
hello
abracadabra
the quick brown fox jumps over the lazy dog
3 rows selected.
test@ORA10G>
test@ORA10G>pratz -
Hi,
I am new to Java. What's the most efficient way to count the number of characters in a string. I have a string of text called MyText. I was thinking of a for loop but maybe there is better solution?
Regards,
Rob.FYI:
public static void main(String[] args)
String word;
System.out.println("Enter word");
word = EasyScanner.nextString();
word.length(); // this is redundant and serves no purpose
System.out.println(word.length());
}Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
// your code block goes here.
[/code]Your posted code will need to be properly formatted to begin with for this to work.
Good luck.
Edited by: Encephalopathic on Jan 6, 2008 10:45 AM -
Replace characters in a string
Hi,
I need to replace all occurrences of control characters except space,newline,tabs in a string . I can give a replace statement for each of these characters but I want to avoid this by making use of regular expressions. Can anyone help me in this regard.
I tried using the following replace statements with regular expression, but i am not getting the required results:
replace all occurrences of REGEX '[[:cntrl:]]' in lv_char with space replacement count lv_count_r.
---> this replaces even the spaces
replace all occurrences of REGEX '[[:cntrl:]][^[:space:]]' in lv_char with space replacement count lv_count_r.
--> this replaced even some alpha numeric characters
Thanks and Regards,
Shankaris there anyway to do this without using regular
expressions.. regular expressions are the last
solution for me..Remember that you can never really replace the characters of a String. Strings are immutable. Once created they cannot change. -
Specify characters in a string
I'm a beginner at Java.
I need to create a program that will validate only binary characters in a string and count the number of 0s in the string. For some reason I keep getting an error message. For the life of me, I can't figure it out.
char a = '1';
char b = '0';
int hmo;
int totalzeroes=0;
String input = JOptionPane.showInputDialog(null, "Please Enter a Binary Number");
for (hmo=0; hmo<input.charAt(hmo);hmo++)
System.out.println(input.charAt(hmo));
totalzeroes++;
OUTPUT:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
at java.lang.String.charAt(Unknown Source)
at cop.main(cop.java:19)...hmo<input.charAt(hmo)...You have to loop up to input.length(), not to the value of the character at certain position.
Mike -
Specify Valid Characters in a String
I'm a beginner at Java.
I need to create a program that will validate only binary characters in a string and count the number of 0s in the string. For some reason I keep getting an error message. For the life of me, I can't figure it out.
char a = '1';
char b = '0';
int hmo;
int totalzeroes=0;
String input = JOptionPane.showInputDialog(null, "Please Enter a Binary Number");
for (hmo=0; hmo<input.charAt(hmo);hmo++)
System.out.println(input.charAt(hmo));
totalzeroes++;
OUTPUT:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
at java.lang.String.charAt(Unknown Source)
at cop.main(cop.java:19)>Just a suggestion.. for this kind of stuff you should probably use regular expressions.. You can easily validate that a string contains only 0 and 1 with something like this:
public boolean validate(String s)
String PATTERN = "[01]+";
Pattern pattern = Pattern.compile(PATTERN, Pattern.CANON_EQ);
Matcher matcher = pattern.matcher(s);
if (matcher.matches())
return true;
else
return false;
Here, you can easily change the PATTERN if you want the string to match something else.. -
How to search special characters in a string
Hi all,
I want to search special characters in all string columns and all rows in the table.
The table has about 5 string columns and about 5.000.000 rows. For each row and column, I have to search entries, which included special characters like ", !, ? or something else (f.ex. "Mama?Mia" or "!!!Hotel out of order!!!"). The problem, the character could stand at each position in the string.
What's the best and most performance possibility to search such entries?? Is it possibility only by SQL; is there a special function for this?? Or must I use PL/SQL.
Thanks for helping
DanaHTH
Laurent Schneider
OCM DBA
SQL> select * from z;
S
Mama?Mia
a b c
123
SQL> select * from z where translate(s,'~ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890','~') is not null;
S
Mama?Mia
SQL> select * from z where regexp_like(s, '[^[:alnum:][:space:]]');
S
Mama?Mia -
How do I drop the last 3 characters in a string?
Hello. I'm trying to find a way to drop the last 3 characters in a string. The length varies because it is a last name field. The problem is that when a customer has a suffix on their name, III for example, it is appended to the last name all in the last name field. If I use the ProperCase function, I end up with "Smith Iii". How can I tell it to drop the last 3 characters? I'll then append an UpperCase edition of the last 3 characters to that. Thank you!
Use the instring and right string functions then UpperCase
-
How to find out if there are repeated characters in a string
hey guys
well i kinda have a little problem figuring out how to find out
if there are repeated characters in a string.
if anyone can help, would appreciate it.
thanks
milosTry using the StringTokenizer class. if u already know which character to trace. this could do the job.
eg. String str = "here and there its everywhere";
StringTokenizer st = new StringTokenizer(str, "e");
int rep = st.countTokens(); -
Removing non english characters from my string input source
Guys,
I have problem where I need to remove all non english (Latin) characters from a string, what should be the right API to do this?
One I'm using right now is:
s.replaceAll("[^\\x00-\\x7F]", "");//s is a string having chinese characters.
I'm looking for a standard Solution for such problems, where we deal with multiple lingual characters.
TIA
NitinNitin_tiwari wrote:
I have a string which has Chinese as well as Japanese characters, and I only want to remove only Chinese characters.
What's the best way to go about it?Oh, I see!
Well, the problem here is that Strings don't have any information on the language. What you can get out of a String (provided you have the necessary data from the Unicode standard) is the script that is used.
A script can be used for multiple languages (for example English and German use mostly the same script, even if there are a few characters that are only used in German).
A language can use multiple scripts (for example Japanese uses Kanji, Hiragana and Katakana).
And if I remember correctly, then Japanese and Chinese texts share some characters on the Unicode plane (I might be wrong, 'though, since I speak/write neither of those languages).
These two facts make these kinds of detections hard to do. In some cases they are easy (separating latin-script texts from anything else) in others it may be much tougher or even impossible (Chinese/Japanese). -
Need help in replacing special characters in a string
Hi,
please let me know the best way to replace all the special characters in a string with space.
other than alphabets and numbers
with regards.
sumanth.please let me know the best way to replace all the special characters in a string with space.
other than alphabets and numbers
>
Sumanth Nag Kristam wrote:
> actually i need to replace hexa decimal char 0X1A in a string.... that is 'substitue' as per the chart
> any pointers....
>
> chk the link for the ASCII codes
> http://www.techonthenet.com/ascii/chart.php
But in Hexa decimal value there is no special characters? -
Sample code to identify special characters in a string
Hi,
I need to identify special characters in a string.... could anybody send me some code please.......
Thanks,
Best regards,
Karendata: str(100) type c.
data: str_n type string.
data: str_c type string.
data: len type i.
data: ofst type i.
str = '#ABCD%'.
len = strlen( str ).
do.
if ofst = len.
exit.
endif.
if str+ofst(1) co sy-abcde.
concatenate str_c str+ofst(1) into str_c.
else.
concatenate str_n str+ofst(1) into str_n.
endif.
ofst = ofst + 1.
enddo.
write:/ str.
write:/ str_c.
write:/ 'spacial chracter',20 str_n.
Function module <b>SF_SPECIALCHAR_DELETE</b> <b>DX_SEARCH_STRING</b>
l_address1 = i_adrc-street.
CHECK NOT L_ADDRESS1 IS INITIAL.
len = STRLEN( l_address1 ).
do len times.
if not l_address1+l(1) ca
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '.
if i_adrc-street+l(1) CO sy-abcde.
elseif i_adrc-street+l(1) CO L_NUMCHAR.
exit.
endif.
l = l + 1.
enddo.
data : spchar(40) type c value '~!@#$$%^&()?...'etc.
data :gv_char .
data:inp(20) type c.
take the string length .
len = strlen (i/p).
do len times
MOVE FNAME+T(1) TO GV_CHAR.
IF gv_char CA spchar.
MOVE fnameT(1) TO inp2T(1).
ENDIF.
T = T + 1.
enddo.
REPORT ZEX4 .
PARAMETERS: fname LIKE rlgrap-filename .
DATA: len TYPE i,
T TYPE I VALUE 0,
inp(20) TYPE C,
inp1(20) type c,
inp2(20) type c,
inp3(20) type c.
DATA :gv_char.
data : spchar(20) type c value '#$%^&*()_+`~'.
START-OF-SELECTION.
CONDENSE fname.
len = strlen( fname ).
WRITE:/ len.
DO len TIMES.
MOVE FNAME+T(1) TO GV_CHAR.
IF gv_char ca spchar.
MOVE fnameT(1) TO inpT(1).
ENDIF.
T = T + 1.
ENDDO.
CONDENSE INP.
write:/ 'Special Characters :', inp.
Rewards if useful..........
Minal
Maybe you are looking for
-
Photoshop CC 2014.1 update now available
The Photoshop CC 2014.1 update now available. Today we are releasing an update to Photoshop CC that includes new 3D printing features and enhancements designed to make it easier to create beautiful 3D printed designs and give you more printing option
-
Need Help in SQL command LIKE !
Hi all, plz go through the following sql statement : select last_name from employees where last_name like '%a%e%' or last_name like '%e%a%'; This gives an output where the last_name contains a or e in it. Now what would be the best solution to find t
-
Sales Order Query for in SAP B1
Hi, I Need to generate a report to Calculate the net sales orders for a particular customer in a given period. i can able to calculate the total sales order details itemwise but my query not works when the customer returns the particular products.(
-
Hi - I made a mistake, I guess. I'm tring to upgrade to os 10.85. I now use 10.75. I bought the upgrade and downloaded it, completely I thought... but when I opened it to install it, a warning came up and said I need 10.8 in order to install 10.8
-
How to store the images in tables
how to store the images in tables .what is the use of "clob ,blob"