Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".
If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
Note that str.length() returns the length of a string.
public String firstTwo(String str) {
if(str.length()<2){
return str;
}
else{
return str.substring(0,2);
}
}
I'm wondering is there any other way can solve this question?
Your code looks great! If you wanted to make it shorter you could use the ternary operator:
public String firstTwo(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
I need to count the number of times a letter's present in a String.
For example:
str = "/data/name/data/name"
How do we get the number of / in this string?
val count = str.count { it == '/' }
To be honest, I am not sure whether you need an answer in java or kotlin (your tags include both), so if you need an answer in java:
String input = "/data/name/data/name";
char search = '/';
long count = input.chars().filter(ch -> ch == search).count();
(and if you need a kotlin version, just take a look at #Ivo's answer)
I think you can count with this way,
val str = "/data/name/data/name"
var count = 0
str.forEach {
if(it == '/'){
count++
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Saying that there are String A = "aabbccdd" and String B = "abcd",
is there any way to remove the matching characters of String B towards String A for only one time?
Expected output is A = "abcd".
I know it will solve the problem when using for loops, but is there any simpler way to do it?
For example, using replaceAll or regular expressions?
you can use distinct() method
public static void main(String[] args) {
String str = "aabbccdd";
String result = str.chars().distinct().boxed()
.map(c -> (char) (c.intValue()))
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(result);
}
you can use the regex for that
A = A.replaceAll("([a-z]+)\1","");
can find out more about regex here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a Java programm and I would like to make every character of a word in a String a lowercase character and replace an empty space " " by a "_". So here are some expample:
"Tall Building" --> "tall_building"
"Red Shoes" --> "red_shoes"
"Water" --> "water"
I do not want to use any libarary if that is possible. Would you mind telling me how I can do that? I'd appreciate every comment.
public static String modifyString(String str) {
if (str == null)
return null;
if (str.isEmpty())
return str;
StringBuilder buf = new StringBuilder(str.length());
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
buf.append(ch == ' ' ? '_' : Character.toLowerCase(ch));
}
return buf.toString();
}
P.S. Sure it could be more another solutions e.g. like str.replace(" ", "_").toLowerCase(). My solution uses StringBuilder which is correct way buil String and does not use Regexp. Time complexity is O(n).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi i want to do some validations.I used to put regex in JS but im new to regex in java, so i tried to make up a code on similar lines in java.
Here is what i did.
1)Check whether first character in string is alphanumeric.
2)Check whether the string atleast 1 number.
so i wrote a code, but it is always returning false.I am not sure if i'm doing this correctly.
private static boolean checkEmbeddedPassword(final String field) {
boolean returnValue=true;
String testpatternAlpha="/^[A-Za-z0-9].+$/";
String testNumber="/[0-9]/";
Pattern pattern=Pattern.compile(testpatternAlpha);
Pattern pattern2=Pattern.compile(testNumber);
Matcher matcher = pattern.matcher(field);
Matcher matcher2 = pattern2.matcher(field);
boolean firstChar=matcher.matches();
boolean numberFlag=matcher2.matches();
System.out.println("-----the value of pwd iss-----"+field);
System.out.println("---------Regex---------Out--put-----"+firstChar);
System.out.println("---------Regex---------Out- for numeral-put-----"+numberFlag);
if(firstChar){
returnValue=false;
}
else if(field.contains(" "))
{
System.out.println("-----------cannot have space------");
returnValue=false;
}
else if(numberFlag)
{
returnValue=false;
}
return returnValue;
}
You don't need the / prefix and suffix in Java:
String testpatternAlpha="^[A-Za-z0-9].+$";
Also in your situation you'll want to be using Matcher.find rather than Matcher.matches. You can read why in the API documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html
we do not use / on the beginning and end of the regex in java.
try this...
String testpatternAlpha="^[A-Za-z0-9].+$"; // first character in string is alphanumeric
String testNumber="[0-9]"; //test single number
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have sentences like:
Slno:0 ahdhajdhjahdjahjdhahd <>
Slno:1 ahdhajdhjahdjahjdhahd <>
Slno:2 ahdhajdhjahdjahjdhahd <>
I want to compare with the first 5 charters as "Slno:x" where x is a integer.
if that condition is met I want to print the rest of the lines. and the remove the last <>
so the output looks like:
ahdhajdhjahdjahjdhahd
ahdhajdhjahdjahjdhahd
ahdhajdhjahdjahjdhahd
I tried doing:
if string1.charAt(1)=='S' for all charcaters and than printed from string1[5] to end.
if that conditions are true. Looking for a more better logic
If i understand your requirement correctly i think this would work.try this:
public static void main(string..args) {
String s1= "Slno:0 ahdhajdhjahdjahjdhahd <>";
String[] sSplit = s1.split("\\s");
String f[]= sSplit[0].split(":");
;
if(f[0].equals("Slno") && checkInt(f[1])) {
System.out.println(sSplit[1]);
}
}
public static boolean checkInt(String i) {
try {
Integer.parseInt(i);
return true;
}
catch(Exception ex){
return false;
}
}
You can use Regex and substring.. if you spaces between your sentences: -
String s1 = "Slno:0 ahdhajdhjahdjahjdhahd <>";
if (s1.substring(0, 6).matches("Slno:\\d")) {
System.out.println(s1.substring(7, s1.length() - 3));
}
Output: -
ahdhajdhjahdjahjdhahd
You can try this,
Example: "Slno:0 ahdhajdhjahdjahjdhahd <>"
Split the Sentence to three parts using split method setting delimiters as space.
StringOne = "Slno:0"
StringTwo = "ahdhajdhjahdjahjdhahd"
StringThree = "<>"
Use contains method to match the input. If the given input matches the first part of the string then print the second part of the string.