Hacker Rank Java String Tokens - java

I'm working on the Java String Tokens on HackerRank. My code is as following:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Write your code here.
scan.close();
// if length is 0
if (s.length() == 0 || s == null) {
System.out.println(0);
return;
}
// It seems we need to remove some spaces
s = s.trim();
String[] words = s.split("[ |!|,|\\?|\\.|_|'|#|]+");
System.out.println(words.length);
for (String word: words){
System.out.println(word);
}
}
}
It has passed most tests but failed when the input is null. I've attached a screenshot in this question:
So, can anyone plz explain what happened here? And how can I fix it?
Thank you so much!

Regex "[ |!|,|\\?|\\.|_|'|#|]+" is extraneous.
Do not separate characters in a [ ] character class by the | OR pattern, since that pattern only applies outside a character class.
There is no need to escape ? and . in a character class, since they are not special characters there.
Correct regex would be [ !,?._'#]+ or [^A-Za-z]+.
The main problem with the code in the question is that split() may return an array where the first element is an empty string.
Example 1: Input ",X," will return ["", "X"]. The empty string before the leading , is included, and the empty string after the trailing , is excluded, because the javadoc says so: "Trailing empty strings are therefore not included in the resulting array".
Example 2: Input "" will return [""], because the javadoc explicitly says so: "If the expression does not match any part of the input then the resulting array has just one element, namely this string". Note how the "trailing empty string" rule is not applied to this specific use case.
Example 3: Input ",," will return [], because trailing empty strings are excluded.
In examples 1 and 2, that leading empty string should be ignored.
I'll leave the actual fixing of the code to you, since this is your challenge to solve.

if (scan.hasNext()) {
s = scan.nextLine();
} else {
System.out.println(0);
return;
}
I edited your code a bit. For no String you have to use Scanner.hasNext(). If there is a String you will read it, otherwise just return and print 0.

The solution success with all test case
package com.example;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.length() > 1 && s.length() < 400000) {
String textFiltered = s.trim();
if (textFiltered.length() > 0) {
String[] words = textFiltered.split("[!,?.*_'#\\ ]+");
int count = words.length;
System.out.println(count);
for (String word : words) {
System.out.println(word);
}
} else {
System.out.println(0);
}
} else {
System.out.println(0);
}
scan.close();
}
}

The issue is with .trim(), move it before s.length()
my working code
import java.util.*;
public class StringTokens {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Write your code here.
s = s.trim();
// if length is 0
if (s.length()>400000){
return ;
}else if (s.length()==0 || s == null){
System.out.println(0);
return ;
}else{
// It seems we need to remove some spaces
String[] words = s.split("[!,?.*_'#\\ ]+");
int count = words.length;
System.out.println(count);
for (String word : words){
System.out.println(word);
}
scan.close();
}
}

Need remove leading empty element in tokens array.
private static String[] getTokens(String s) {
if (s == null || s.isEmpty()) {
return new String[0];
}
String[] tokens = s.trim().split("[^a-zA-Z]+"); // or [^A-Za-z]+
if (tokens != null && tokens.length > 0 ) {
if (tokens[0].isEmpty()) {
return Arrays.copyOfRange(tokens, 1, tokens.length);
} else {
return tokens;
}
}
return new String[0];
}

Related

How do I replace more than one type of Character in Java String

newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string

Java - Word Count True or False

i have a programming task using java...
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
int wordcount = 0;
for(int i = 0; i < sentence.length()-1; i++) {
if(sentence.charAt(i) == ' ' && Character.isLetter(sentence.charAt(i+1)) && (i > 0)) {
wordcount++;
}
}
wordcount++;
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}}
My question is how can i define the String sentence based on this condition:
If more than 3 words, it will be True.
If less than 4 words, it becomes False.
Thankyou so much for helping..
If I understand your question correctly...
/* returns string array of tokens (words in the sentence) after splitting by space */
String[] tokens = sentence.split(" ");
if(tokens.length() > 3) {
// true
} else {
// fasle
}
Let's have a look at the steps we should take in order to achieve your goal in a easier way;
First , let's count the number of words in your input string via
count function
Call the function by sending our input sentence
Function returns number of words Check the number of words for any
condition you desire
Therefore your code will work better like this;
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
private bool coniditon;
int wordcount = count(sentencte);
if (wordcount<4) {
condition=False;
}
else if (wordcount>3) {
condition=True;
}
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}
public static int count(String sentence){
if(sentence == null || sentence.isEmpty()){
return 0; }
String[] words = sentence.split("\\s+");
return words.length; }
}
}
Good luck!

How to check if a string contains only letters?

How to check if a string contains only letters? is there any specific functions that does that ?
I don't know about a direct function But you can follow these steps :
1) Take a string as input
2) By using toLower() method, convert everything into lower case
3) Use toCharArray() method of the String class to convert into a character array
4) Now check whether at every location has character between a to z
code :
import java.util.Scanner;
public class StringValidation{
public boolean validtaeString(String str) {
str = str.toLowerCase();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char ch = charArray[i];
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
StringValidation obj = new StringValidation();
boolean bool = obj.validtaeString(str);
if(!bool) {
System.out.println("Given String is invalid");
}else{
System.out.println("Given String is valid");
}
}
}
Here is the output:
Output:
Enter a string value:
24stackoverflow
Given String is invalid
------------------------
Enter a string value:
StackOverflow
Given String is valid
You can use a regex to test if a string matches the pattern /^[a-z]+$/i if you're only concerned about simple English unaccented letters.
For letters in many languages, you can use /^\p{L}+$/i.
As Java regexes, these look like:
Pattern.compile("^[a-z]+$", Pattern.CASE_INSENSITIVE)
Pattern.compile("^\\p{L}+$")
Update: {L} works better than {Alpha} for accented characters.
pattern = Pattern.compile("^\\p{L}+$");
System.out.println(pattern.matcher("foo").matches());
System.out.println(pattern.matcher("Foo").matches());
System.out.println(pattern.matcher("föo").matches());
System.out.println(pattern.matcher("fo-oo").matches());
Try StringUtils.isAlpha.
See: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isAlpha-java.lang.CharSequence-
I see the answer and I want to add another solution, I preferred this solution because is more personalizable.
The class Character has the method, like.isLetter(). you can see also the java documentation
I have a code example like this:
public class CheckLetterInTheString {
public static boolean isOnlyLetter(String string){
if(string == null || string.isEmpty()){
throw new IllegalArgumentException("String not valid");
}
char[] chatString = string.toCharArray();
for(Character character : chatString){
if(!Character.isLetter(character) && !Character.isSpaceChar(character)){
return false;
}
}
return true;
}
}
now you can call
System.out.println(CheckLetterInTheString.isOnlyLetter("String only letter")); //true
System.out.println(CheckLetterInTheString.isOnlyLetter("Contains num 12")); //false
P.S: I like this solution because is more personalizable and I think it is more readable than a regex. But is only my opinion

Make String first letter capital in java

As of now I'm using this code to make my first letter in a string capital
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
This seems very dirty to me ..is there any direct or elegant way..
How about this:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.
You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()
Description from the lib:
Capitalizes a String changing the first letter to title case as per
Character.toTitleCase(char). No other letters are changed.
String out = Character.toUpperCase(inText.charAt(0)) + inText.substring(1).toLowerCase();
public static void main(String[] args) {
String str = null;
String outStr = null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
str = sc.nextLine();
//c= Character.toUpperCase(str.charAt(0));
for(int i=0; i< (str.length());i++){
if(str.charAt(i)==' '){
outStr= outStr.substring(0,i+1)+str.substring(i+1,i+2).toUpperCase()+str.substring(i+2);
}else if(i==0){
outStr=str.substring(0,1).toUpperCase()+str.substring(1);
}
}
System.out.println("STRING::"+outStr);
}
Assuming you can use Java 8, here's the functional way that nobody asked for...
import java.util.Optional;
import java.util.stream.IntStream;
public class StringHelper {
public static String capitalize(String source) {
return Optional.ofNullable(source)
.map(str -> IntStream.concat(
str.codePoints().limit(1).map(Character::toUpperCase),
str.codePoints().skip(1)))
.map(stream -> stream.toArray())
.map(arr -> new String(arr, 0, arr.length))
.orElse(null);
}
}
It's elegant in that it handles the null and empty string cases without any conditional statements.
Character.toString(a.charAt(0)).toUpperCase()+a.substring(1)
P.S = a is string.
Here, hold my beer
String foo = "suresh";
String bar = foo.toUpperCase();
if(bar.charAt[0] == 'S'){
throw new SuccessException("bar contains 'SURESH' and has the first letter capital").
}
class strDemo3
{
public static void main(String args[])
{
String s1=new String(" the ghost of the arabean sea");
char c1[]=new char[30];
int c2[]=new int[30];
s1.getChars(0,28,c1,0);
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
for(int i=1;i<s1.length();i++)
{
c2[i]=c1[i];
if(c1[i-1]==' ')
{
c2[i]=c2[i]-32;
}
c1[i]=(char)c2[i];
}
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
}
}

Removing contiguous spaces in a String without trim() and replaceAll()

I have to remove leading and trailing spaces from the given string as well as combine the contiguous spaces. For example,
String str = " this is a string containing numerous whitespaces ";
and I need to return it as:
"this is a string containing numerous whitespaces";
But the problem is I can't use String#trim(). (This is a homework and I'm not allowed to use such methods.) I'm currently trying it by accessing each character one-by-one but quite unsuccessful.
I need an optimized code for this. Could anybody help? I need it to be done by today :(
EDIT: Answer posted before we were told we couldn't use replaceAll. I'm leaving it here on the grounds that it may well be useful to other readers, even if it's not useful to the OP.
I need an optimized code for this.
Do you really need it to be opimtized? Have you identified this as a bottleneck?
This should do it:
str = str.replaceAll("\\s+", " ");
That's a regular expression to say "replace any contintiguous whitespace with a single space". It may not be the fastest possible, but I'd benchmark it before trying anything else.
Note that this will replace all whitespace with spaces - so if you have tabs or other whitespace characters, they will be replaced with spaces too.
I'm not permitted to use these methods. I've to do this with loops
and all.
So i wrote for you some little snipet of code if you can't use faster and more efficient way:
String str = " this is a string containing numerous whitespaces ";
StringBuffer buff = new StringBuffer();
String correctedString = "";
boolean space = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
if (!space && i > 0) {
buff.append(c);
}
space = true;
}
else {
buff.append(c);
space = false;
}
}
String temp = buff.toString();
if (temp.charAt(temp.length() - 1) == ' ') {
correctedString = temp.substring(0, buff.toString().length() - 1);
System.out.println(correctedString);
}
System.out.println(buff.toString())
Note:
But this is "harcoded" and only for "learning".
More efficient way is for sure use approaches pointed out by #JonSkeet and #BrunoReis
What about str = str.replaceAll(" +", " ").trim();?
If you don't want to use trim() (and I really don't see a reason not to), replace it with:
str = str.replaceAll(" +", " ").replaceAll("^ ", "").replaceAll(" $", "");`
Remove White Spaces without Using any inbuilt library Function
this is just a simple example with fixed array size.
public class RemWhite{
public static void main(String args[]){
String s1=" world qwer ";
int count=0;
char q[]=new char[9];
char ch[]=s1.toCharArray();
System.out.println(ch);
for(int i=0;i<=ch.length-1;i++)
{
int j=ch[i];
if(j==32)
{
continue;
}
else
q[count]=ch[i];
count++;
}
System.out.println(q);
}}
To remove single or re-occurrence of space.
public class RemoveSpace {
public static void main(String[] args) {
char space = ' ';
int ascii = (int) space;
String str = " this is a string containing numerous whitespaces ";
char c[] = str.toCharArray();
for (int i = 0; i < c.length - 1; i++) {
if (c[i] == ascii) {
continue;
} else {
System.out.print(c[i]);
}
}
}
}
If you don't want to use any inbuilt methods here's what you refer
private static String trim(String s)
{
String s1="";boolean nonspace=false;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=' ' || nonspace)
{
s1 = s1+s.charAt(i);
nonspace = true;
}
}
nonspace = false;
s="";
for(int i=s1.length()-1;i>=0;i--)
{
if(s1.charAt(i)!=' ' || nonspace)
{
s = s1.charAt(i)+s;
nonspace = true;
}
}
return s;
}
package removespace;
import java.util.Scanner;
public class RemoveSpace {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the string");
String str= scan.nextLine();
String str2=" ";
char []arr=str.toCharArray();
int i=0;
while(i<=arr.length-1)
{
if(arr[i]==' ')
{
i++;
}
else
{
str2= str2+arr[i];
i++;
}
}
System.out.println(str2);
}
}
This code is used for removing the white spaces and re-occurrence of alphabets in the given string,without using trim(). We accept a string from user. We separate it in characters by using charAt() then we compare each character with null(' '). If null is found we skip it and display that character in the else part. For skipping the null we increment the index i by 1.
try this code to get the solution of your problem.
String name = " abc ";
System.out.println(name);
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == ' ') {
i = 2 + i - 2;
} else {
System.out.print(name.charAt(i));
}
}

Categories