How to check how many letters are in a string in java? - java

How do you check how many letters are in a Java string?
How do you check what letter is in a certain position in the string (i.e, the second letter of the string)?

A)
String str = "a string";
int length = str.length( ); // length == 8
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29
edit
If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
where TestCase can be isLetter( ), isDigit( ), etc.
Or if you just want to count everything but spaces, then do a check in the if like temp != ' '
B)
String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:
String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // 瘌фγε𐍅
The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc
sample.codePointCount(0, sample.length()) // returns 5
http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

To answer your questions in a easy way:
a) String.length();
b) String.charAt(/* String index */);

1) To answer your question:
String s="Java";
System.out.println(s.length());

I could not get any of these answers to work for me using UTF-8. If you are using UTF-8, have a look at this post. I ended up using Guava's Utf8.

Related

How can I get all the characters after a certain number of digits in a string in Java?

My question is fairly simple. I want to get all the characters in a string after a certain number of digits. For example, if I entered in 123 InsertIGN, I want to know how I can get all the characters after 123, no matter how many of them are there. I want it to still work if I entered 123 VeryLongWordHereshfusihdisa. I would want to get everything AFTER 123. Is there any way I can go about doing that? Sorry for the dumb question, I stopped coding in Java for a while and recently have come back. Thanks in advance for any answers!
If your test case is "123" always in the first place of string. You can use substring as simple as
String testCase = "123ABCD!##$";
String result = testCase.substring("123".length());
Or if your test case would be "123" is in random place, but still could get all the chars behind that. We can hack it to
String testCase = "ABCD123!##$";
String splitBy
int index123 = testCase.indexOf("123") + "123".length();
String result = testCase.substring("123".length());
it will return
result = !##$
Using index123 object we are trying to get the position of the first "123" without "123" thats why we need to add length of "123".
Let's try using another test case
String testCase = "ABCD123!##$123XYZ";
will return
result = !##$123XYZ
Because we only process the first "123"
Get the Unicode code point integer assigned to each character in your input string.
String input = "123 InsertIGN" ;
List< Integer > codePoints = input.codePoints().boxed().toList() ;
Loop each code point. Ask if that character is a digit. If so, increment a count. Once your desired limit is reached, collect remaining characters.
StringBuilder result = new StringBuilder() ;
int limit = 3 ; // Number of digit occurrences to get past.
int count = 0 ;
for( Integer codePoint : codePoints )
{
if( count < limit )
{
if( Character.isDigit( codePoint ) ) { count ++ ; }
}
else
{
result.append( codePoint ) ;
}
}
There are nifty ways to do that with streams. But as someone returning to Java programming, you may not be familiar with that. So the above is the old-school approach.

Check if all characters in string are the same with inbuilt methods without loops

How can I build a Java method that returns TRUE if all the characters in a String are the same using inbuilt methods - without using Regex, loops, or recursion?
Examples:
aaaaaa --> True
abaaaa --> False
Aaaaaa --> False
You can convert the string to an IntStream using .chars() and check if the stream has distinct count of 1 using .distinct().count() == 1.
String s = "aaaaaa";
boolean isAllCharsSame = s.chars().distinct().count() == 1;
isAllCharsSame will be true if all characters in the string s are same, otherwise false.
Edit:
String s = "aaaaaa";
boolean isAllCharsSame = s.codePoints().distinct().count() == 1;
.chars() won't work for Unicode codepoints like "👋👋👋", use .codePoints() for that. Thanks to #BasilBourque for pointing this out.
tl;dr
if ( "👋👋👋".codePoints().distinct().count() == 1 ) { … }
Code point, not char
Some of the other Answers use char. Unfortunately the char type is obsolete, unable to represent even half of the 143,859 characters in Unicode. Just try using the string "👋👋👋" instead of "aaa".
Instead use code point integer numbers.
Set < Integer > codePointsDistinct = "aaaaaaa".codePoints().boxed().collect( Collectors.toSet());
boolean allSameCharacter = ( codePointsDistinct.size() == 1 ) ;
See that code run live at IdeOne.com.
true
We can make that even more brief by asking the stream to eliminate duplicates by calling .distinct().
boolean allSameCharacter = ( "👋👋👋".codePoints().distinct().count() == 1 );
You can use String.replaceAll()
String s = "aaaaaaa";
boolean same = s.replaceAll("" + s.charAt(0), "").length() == 0;
You can do it without a loop at all, using recursion. It's awful, but possible:
boolean singleChar(String s) {
// Add check to make sure there is at least one char.
char first = s.charAt(0);
return singleCharRecursive(first, 1, s);
}
boolean singleCharRecursive(char first, int idx, String s) {
return idx >= s.length()
|| (s.charAt(idx) == first && singleCharRecursive (first, idx+1, s));
}
Here's another answer
I believe there maybe another option analyzing off the first character in the string to see if they all match, but this one works.
String t = "aaa";
char c = t.charAt(0);
long cnt = t.chars().filter(ch -> ch == c).count();
System.out.println(cnt==t.length());
You can use replace method:
boolean r = "aaaaaaa".replace("a", "").length() == 0;
System.out.println(r); // true
See also: Easier way to represent indicies in a 2D array

Java pad string with specific characters

I have a string apple I want it maximum 8 character long.
So i have apple. its 5 chars long. I pad it with 3* to make it ***apple
So i have bat. its 3 chars long. I pad it with 5* to make it *****bat
Is there any way to do it? Cant find any padding library out there.
Other way how you can do it:
String.format("%8s", "helllo").replace(' ', '*');
In this case you do not need to add library.
tl;dr
Built into Java 11+
"*" // A single-character string.
.repeat( 8 - "apple".length ) // `String::repeat` multiplies text. Here we return a `String` of a certain number of asterisks.
.concat( "apple" ) ; // Appends to those asterisks our original input.
***apple
String::repeat
Java 11 brought a new method, repeat, to the String class. This method multiplies a piece of text a certain number of times. Multiplying by zero is valid, resulting in an empty string.
In our case, we want to multiply a single character string, *.
int goal = 8 ;
String input = "apple" ;
int length = input.length() ;
String output = "*".repeat( goal - length ).concat( input ) ;
See this code run live at IdeOne.com.
***apple
No library needed. Uses a StringBuilder and reverse() for speed (insert is slower than append):
public String padWord(String word)
{
if(word.length() < 8)
{
StringBuilder foo = new StringBuilder(word);
foo = foo.reverse();
for(int x = word.length(); x < 8; x++)
{
foo.append('*');
}
foo.reverse();
}
return foo.toString();
}
You can use StringUtils.leftPad from Apache Commons Lang library
StringUtils.leftPad(null, *, *) = null
StringUtils.leftPad("", 3, 'z') = "zzz"
StringUtils.leftPad("bat", 3, 'z') = "bat"
StringUtils.leftPad("bat", 5, 'z') = "zzbat"
StringUtils.leftPad("bat", 1, 'z') = "bat"
StringUtils.leftPad("bat", -1, 'z') = "bat"

Finding Letter Combinations

For a string such as -u--('-' indicates a blank space), i'm given a letter lets say "d". The goal is for me to find all the combinations in which the letter d can be substituted in for the "-". A little hard to explain but, this is what an intended output would look like:
du--
dud-
du-d
dudd
-ud-
-udd
-u-d
I can't seem to find a set way of finding the combinations because I need to be able to find combinations of various lengths such as:
-u-----, or ----u-
Thanks for any future help, if more clarification is needed I can try to explain a little better.
This is best done recursively.
Base case: combinations of the empty string are [].
Recursive case 1: to get combinations of u....., get all combinations of .....; then prefix each one with "u".
Recursive case 2: to get combinations of -....., get all combinations of .....; then prefix each one with "d", and prefix each one with -, and concatenate the two arrays.
This is my solution to your problem:
public String[] getCombinations( String inputString ) {
int dashCount = 0;
for( int i = 0; i < inputString.length(); i++ ) { // checks how many '-' you have in the String
if( inputString.charAt(i) == '-' ) dashCount++;
}
int uPosition = inputString.indexOf('u');
ArrayList<String> arr = new ArrayList<String>();
for( int i = 1; i <= Math.pow(2,dashCount)-1; i++ ) {
String temp = String.format("%"+dashCount+"s", Integer.toBinaryString(i)).replace(' ', '0'); // this returns a dashCount-bit binary number like 0001, 0010, for a dashCount of 4
temp = temp.replace( '0', '-' );
temp = temp.replace( '1', 'd' );
arr.add( temp.substring(0,uPosition) + "u" + temp.substring(uPosition, temp.length()) );
}
Object[] tempArr = arr.toArray();
return Arrays.copyOf(tempArr, tempArr.length, String[].class);
}
Idea is, treat all '-' as bits in a binary number, so count all occurrences of '-'. For convenience, we say we have n bits in the binary number.
Numbers from 1 to (2^n)-1 in binary will yield all possible combinations of 1's and 0's for the string.
Swap all '0' with '-', and swap all '1' with 'd'.
Insert 'u' to its original position.
Boom.
EDIT: altered code so you don't need third-party libraries.

Get int from String, also containing letters, in Java

How can I get the int value from a string such as 423e - i.e. a string that contains a number but also maybe a letter?
Integer.parseInt() fails since the string must be entirely a number.
Replace all non-digit with blank: the remaining string contains only digits.
Integer.parseInt(s.replaceAll("[\\D]", ""))
This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.
If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:
s.matches("[\\d]+[A-Za-z]?")
The NumberFormat class will only parse the string until it reaches a non-parseable character:
((Number)NumberFormat.getInstance().parse("123e")).intValue()
will hence return 123.
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
You can also use Scanner :
Scanner s = new Scanner(MyString);
s.nextInt();
Just go through the string, building up an int as usual, but ignore non-number characters:
int res = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
res = res * 10 + (c - '0');
}
Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().
Something like:
String something = "423e";
int length = something.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = something.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("result is: " + result);

Categories

Resources