How to check if all characters in a String are all letters? - java

I'm able to separate the words in the sentence but I do not know how to check if a word contains a character other than a letter. You don't have to post an answer just some material I could read to help me.
public static void main(String args [])
{
String sentance;
String word;
int index = 1;
System.out.println("Enter sentance please");
sentance = EasyIn.getString();
String[] words = sentance.split(" ");
for ( String ss : words )
{
System.out.println("Word " + index + " is " + ss);
index++;
}
}

What I would do is use String#matches and use the regex [a-zA-Z]+.
String hello = "Hello!";
String hello1 = "Hello";
System.out.println(hello.matches("[a-zA-Z]+")); // false
System.out.println(hello1.matches("[a-zA-Z]+")); // true
Another solution is if (Character.isLetter(str.charAt(i)) inside a loop.
Another solution is something like this
String set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String word = "Hello!";
boolean notLetterFound;
for (char c : word.toCharArray()){ // loop through string as character array
if (!set.contains(c)){ // if a character is not found in the set
notLetterfound = true; // make notLetterFound true and break the loop
break;
}
}
if (notLetterFound){ // notLetterFound is true, do something
// do something
}
I prefer the first answer though, using String#matches

For more reference goto-> How to determine if a String has non-alphanumeric characters?
Make the following changes in pattern "[^a-zA-Z^]"

Not sure if I understand your question, but there is the
Character.isAlpha(c);
You would iterate over all characters in your string and check whether they are alphabetic (there are other "isXxxxx" methods in the Character class).

You could loop through the characters in the word calling Character.isLetter(), or maybe check if it matches a regular expression e.g. [\w]* (this would match the word only if its contents are all characters).

you can use charector array to do this like..
char[] a=ss.toCharArray();
not you can get the charector at the perticulor index.
with "word "+index+" is "+a[index];

Related

Check if string contains any part of substring

I have
String S = "Eng - Computer, Eng - Software.."
User inputs:
String I = "Engineering."
I would like this to return true because S contains "Eng" part of a substring of I.
How can I do this?
S.trim.toLowercase.contains(....)
Does not properly work because of the "part" of substring.
Is S a standard string that checks if a substring which enters a user is part of S?
If so, you can use the "contains" method:
if (I.contains("*/string that you want to check*/")
return true;
It depends on what you mean. Are you looking if any of the words in S are contained in I? If that's the case, I would recommend splitting S into an array of Strings for each word, and then checking if any of the words are a substring of I. Take a look at this function.
public boolean checkSubstring(String S, String I){
String[] words = S.split(" ");
for(int i=0; i<words.length; i++){
if(I.contains(words[i])
return true; //We found a word contained in I!
}
return false; //None of the words were contained in I
}
Try the code below:
You need to tokenize S and then ask if I contains any of those tokens.
String S = "Eng - Computer, Eng - Software..";
String I = "Engineering.";
//neither S or I contain each other
System.out.println(S.trim().toLowerCase().contains(I));
System.out.println(I.trim().toLowerCase().contains(S));
String[] tokens = S.split(" ");
//but parts of S are contained in I...
for(String token : tokens) {
if(I.contains(token)) {
System.out.println("found : " +token);
}
}

How to print a letter of a word using a number?

I'm relatively new to coding and my teacher asked us to make a code for a hangman game. He told us that we must accomplish this without the use of Arrays. My question is along the lines of this: If I have a String that is declared by the user and then a correct letter is guessed, how would I specifically be able to replace a substituted underscore with the guessed letter?
For example...
input is "cats"
system types "_ _ _ _"
say I typed the letter "a" and I want the output to be:
"_ a _ _"
How would I get the placement number of that letter and then manipulate the underscore to make it the letter?
StringBuilder.charAt()
StringBuilder.setCharAt()
You may want to have a look at these methods.
For the purpose of printing, you may want StringBuilder.toString().
You could use substrings. Something like this.
String original = "apple";
String guessed = original;
String withUnderscores = "_____";
String guess = "a";
while (guessed.contains(guess))
{
int index = guessed.indexOf(guess);
withUnderscores = withUnderscores.substring(0, index) + guess + withUnderscores.substring(index + 1);
guessed = guessed.substring(0, index) + "." + guessed.substring(index + 1);
}
System.out.println(original);
System.out.println(guessed);
Use one variable to store the underscore string. (ie "____"
Use another variable to store the answer string. (ie "cats").
Get the users input and and loop through the string taking the character at each index. If any variable matches the input letter (string1.equals(string2)) replace the character in the underscore string at whatever index your loop is at.
Use charAt() to get the character at a place in a string.
You can do this with a String or the StringBuilder class. If you haven't learned about StringBuilder in your classes, you probably shouldn't use it for your assignment.
Try something like this (I would prefer to have the guesses on a Set, it would be more clear than using a string to hold them):
public String maskUnguessedLetters(String answer, String guessed) {
Char MASKED = '_';
StringBuilder sb = new StringBuilder();
for (Char c : answer.toCharArray()) {
sb.append(guessed.contains(c.toString())
? c
: MASKED);
}
return sb.toString();
}
I don't completely understand the question, but I think this might help.
final String trueWord="cats";
String guessWord="____";
String input="a";
//if the input matches
if(trueWord.contains(input)){
//last Index of input in trueWord
int lastEntry=-1;
//hold all indices of input character in trueWord
ArrayList<Integer> indices=new ArrayList<>();
while(trueWord.indexOf(input,lastEntry+1) >= 0){
lastEntry=trueWord.indexOf(input);
indices.add(lastEntry);
}
//now replace the characters at the indices
StringBuilder newGuessWord = new StringBuilder(guessWord);
for(int index:indices){
//replace one character at a time.
newGuessWord.setCharAt(index, input.charAt(0));
}
//the new word
guessWord=newGuessWord.toString();
}
This is the not the most optimised code but will definitely give you an idea of how your task can be done.
public static void main(String[] args) {
final String word = "cats";
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the character");
String finalString = "";
char letter = scanner.next().charAt(0);
for (char s : word.toCharArray()) {
if (s == letter) {
finalString += s;
} else
finalString += "_";
}
System.out.println(finalString);
scanner.close();
}

Convert String into Title Case

I am a beginner in Java trying to write a program to convert strings into title case. For example, if String s = "my name is milind", then the output should be "My Name Is Milind".
import java.util.*;
class TitleCase
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
String str ="";
char a ;
for(int i =0;i<s.length()-1;i++)
{
a = s.charAt(i);
if(a==' ')
{
str = str+(Character.toUpperCase(s.charAt(i+1)));
}
else
{
str =str+(Character.toLowerCase(a));
}
}
//for(int i =0; i<s.length();i++)
//{
System.out.println(str);
//}
}
}
You are trying to capitalize every word of the input.
So you have to do following steps:
get the words separated
capitalize each word
put it all together
print it out
Example Code:
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
//now your input string is storred inside s.
//next we have to separate the words.
//here i am using the split method (split on each space);
String[] words = s.split(" ");
//next step is to do the capitalizing for each word
//so use a loop to itarate through the array
for(int i = 0; i< words.length; i++){
//we will save the capitalized word in the same place again
//first, geht the character on first position
//(words[i].charAt(0))
//next, convert it to upercase (Character.toUppercase())
//then add the rest of the word (words[i].substring(1))
//and store the output back in the array (words[i] = ...)
words[i] = Character.toUpperCase(words[i].charAt(0)) +
[i].substring(1);
}
//now we have to make a string out of the array, for that we have to
// seprate the words with a space again
//you can do this in the same loop, when you are capitalizing the
// words!
String out = "";
for(int i = 0; i<words.length; i++){
//append each word to out
//and append a space after each word
out += words[i] + " ";
}
//print the result
System.out.println(out);
}
Using Java 8 streams:
String titleCase = (new ArrayList<>(Arrays.asList(inputString.toLowerCase().split(" "))))
.stream()
.map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
The problem is with the way you're adding characters. Take a look at your if condition:
a = s.charAt(i);
if(a==' ')
{
// Here you are adding not the current character, but the NEXT character.
str = str+(Character.toUpperCase(s.charAt(i+1)));
}
else
{
// Here you are adding the current character.
str =str+(Character.toLowerCase(a));
}
As a result of this condition, you will skip a character if your input string contains a space, then repeat another character that you've already added.
Additionally, you're not looping through the whole string because your loop conditional goes to s.length()-1. Change that to just s.length(). However, if you do that, you may run into an exception if the input string ends with a space (since you'll try to check for a character at an out-of-bound index).
Here's what the fixed code would look like:
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
String str ="";
char a ;
for(int i =0;i<s.length();i++)
{
a = s.charAt(i);
if(a==' ')
{
str = str+Character.toLowerCase(a)+(Character.toUpperCase(s.charAt(i+1)));
i++; // "skip" the next element since it is now already processed
}
else
{
str =str+(Character.toLowerCase(a));
}
}
System.out.println(str);
}
NOTE: I only fixed the code that you supplied. However, I'm not sure it works the way you want it to - the first character of the string will still be whatever case it started in. Your conditional only uppercases letters that are preceded by a space.
You want to change the case of the first letter of each word of a String.
To do so, I would follow the following steps :
split the String in words : see String.split(separator)
retrieve the first letter of each word : see String.charAt(index)
retrieve its capitalized version : the Character.toUpperCase(char) you use is perfect
concatenate the capitalized letter with the rest of the word : concatenation operator (+) and String.substring
create a new String from the capitalized words : see String.join(separator)
Code Golf variation... I challenge anyone to make it any simpler than this:
public String titleCase(String str) {
return Arrays
.stream(str.split(" "))
.map(String::toLowerCase)
.map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
}
By the way: Unicode distinguishes between three cases: lower case, upper case and title case. Although it does not matter for English, there are other languages where the title case of a character does not match the upper case version. So you should use
Character.toTitleCase(ch)
instead of Character.toUpperCase(ch) for the first letter.
There are three character cases in Unicode: upper, lower, and title. Uppercase and lowercase are familiar to most people. Titlecase distinguishes characters that are made up of multiple components and are written differently when used in titles, where the first letter in a word is traditionally capitalized. For example, in the string "ljepotica",[2] the first letter is the lowercase letter lj(\u01C9 , a letter in the Extended Latin character set that is used in writing Croatian digraphs). If the word appeared in a book title, and you wanted the first letter of each word to be in uppercase, the correct process would be to use toTitleCase on the first letter of each word, giving you "Ljepotica" (using Lj, which is \u01C8). If you incorrectly used toUpperCase, you would get the erroneous string "LJepotica" (using LJ, which is \u01C7).
[The Java™ Programming Language, Fourth Edition, by James Gosling, Ken Arnold, David Holmes (Prentice Hall). Copyright 2006 Sun Microsystems, Inc., 9780321349804]
WordUtils.capitalizeFully() worked for me like charm as it gives: WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
import java.util.Scanner;
public class TitleCase {
public static void main(String[] args) {
System.out.println("please enter the string");
Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
//whatever the format entered by user, converting it into lowercase
str = str.toLowerCase();
// converting string to char array for
//performing operation on individual elements
char ch[] = str.toCharArray();
System.out.println("===============");
System.out.println(str);
System.out.println("===============");
//First letter of senetence must be uppercase
System.out.print((char) (ch[0] - 32));
for (int i = 1; i < ch.length; i++) {
if (ch[i] == ' ') {
System.out.print(" " + (char) (ch[i + 1] - 32));
//considering next variable after space
i++;
continue;
}
System.out.print(ch[i]);
}
}
}
You can use lamda instead-
String titalName = Arrays.stream(names.split(" "))
.map(E -> String.valueOf(E.charAt(0))+E.substring(1))
.reduce(" ", String::concat);

Remove trailing substring from String in Java

I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}

Splitting a string into two

I am attempting to split a word from its punctuation:
So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.
I tried using .split method but deletes the delimiter (the punctuation) , which means you wouldn't conserve the punctuation character.
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
I am stuck I cant see another method of doing it.
Thanks in advance
You could use a positive lookahead to split so you don't actually use the punctuation to split, but the position right before it:
inWord.split("(?=[,?.!;])");
ideone demo
Further to the other suggestions, you can also use the 'word boundary' matcher '\b'. This may not always match what you are looking for, it detects the boundary between a word and a non-word, as documented: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
In your example, it works, though the first element in the array will be a blank string.
Here is some working code:
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.matches(".*[,?.!;].*")) {
String parts[] = inWord.split("\\b");
word = parts[1];
punctuation = parts[2];
System.out.println(parts.length);
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
You can see it running here: http://ideone.com/3GmgqD
I've also fixed your .contains to use .matches instead.
I think you can use the below regex. But not tried. Give it a try.
input.split("[\\p{P}]")
You could use substring here. Something like this:
String inWord = "hello?";
String word = inWord.substring (0, 5);
String punctuation = inWord.substring (5, inWord.length ());
System.out.println (word);
System.out.println (punctuation);

Categories

Resources