Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need your help with String Java Program
Input : aaabbaaeedddbbbb
Output : a3b2a2e2d3b4
by using Java 8, one interview asking me
by using Groupby,streams
You can use Matcher#replaceAll for this purpose.
String str = "aaabbaaeedddbbbb";
String res = Pattern.compile("(.)\\1*").matcher(str)
.replaceAll(mr -> mr.group(1) + mr.group().length());
System.out.println(res);
Demo
Here is a method using streams.
the regular expression splits between different characters
the map appends the string character and its length.
the collector joins the strings.
String s = "aaabbaaeedddbbbb";
String result = Arrays.stream(s.split("(?<=(.))(?!\\1)"))
.map(str->str.charAt(0)+""+str.length())
.collect(Collectors.joining());
System.out.println(result);
Prints
a3b2a2e2d3b4
Here is one way to do it using groupingBy and streams (as requested in your question). It applies the previous method of splitting the source string.
String result = Arrays.stream(s.split("(?<=(.))(?!\\1)"))
.collect(Collectors.groupingBy((a) -> "result",
Collectors.mapping(
str -> str.charAt(0) + ""
+ str.length(),
Collectors.joining())))
.get("result");
However, imo this is very kludgely and a better way may exist. But even then, it is inferior to other methods and I don't know why an interviewer would ask this.
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 1 year ago.
Improve this question
For example, I have a string String str = "a_B_c", and How to Convert English alphabet in the string to its ASCII value in java while using stream API? Like the result of String str = "a_B_c" is 97_66_99.
I just want to know if this can be done by using java stream api, I will be really appreciate if you post your answer, thx.
To do this, you'd have to stream the string's individual characters. You certainly can. It's unlikely to be particularly nice or efficient; streams are a tool. Writing code presupposing tools is a bad idea. You're asking the equivalent of: "I have some bread and some schmear. I need to put the schmear on the bread. I just bought this shiny new clawhammer, so, I would prefer to use it for this task!".
You can smear a slice of bread with a clawhammer, if you must. It's a bit awkward, though. Is using streams for this as bad? Maybe - but the point is: Don't presuppose tools. Bread is best smeared with a butter knife. If you have one in your drawer than use it.
There's a somewhat (?) common belief that 'streams just make everything better'. That's patently false. It makes things that are well suited to streams a lot better. It usually makes the rest a lot worse, by being non-transparent on various fronts (local mutable variables, exceptions, and control flow), and being less flexible.
You're in luck, here. It's a wash, mostly - this is about as easy with streams as with a for loop.
"a_B_c".chars()
.mapToObj(x -> x == '_' ? "" : String.valueOf(x))
.collect(Collectors.joining("_"));
or possibly:
Arrays.stream("a_B_c".split("_"))
.mapToObj(String::valueOf)
.collect(Collectors.joining("_"));
If I understood your problem/question correctly, you can do this:
String str = "a_B_c";
String[] letters = str.split("_");
Stream<String> letterStream = Arrays.stream(letters);
And then use Stream.map to convert the letters to their char code. And afterwards use Collectors.joining("_") to rebuild the String.
This of course only works correctly if there's only a single letter between each underscore.
The following code should do the job:
private static String foo(String str) {
return str.chars().mapToObj(value -> value == "_".charAt(0) ? "_" : "" + value).collect(Collectors.joining( "" ));
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have the following information
String templateString = "I am %NAME% and I live in %PLACE%";
String inputString = "I am John Doe and I live in New York";
I need to write a function which will take in the above 2 strings and return a HashMap of pairs.
HashMap<String,String> parseInputFromTemplate(templateString, inputString) {
// Magic
return result;
}
The result will have
%NAME% (key) , John Doe (value)
%PLACE% (key) , New York (value)
Any pointers would be appreciated.
You can use regular expressions to extract what you need. Alternatively you can use the split() method to split on "%". Every other string in the resulting array would be a template var. The others would be the static strings to discard in the inputString.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string like this- 11/15/2013.
I want to replace 2013 with 2000 (last 2 digits with 0). how to do this?
You can always do replace date.replace("13", "00");
but if you are looking at something generic of a solution (In case if you are not aware of what the last 2 digits are, yet you want them to be '00') you can do something like this :
String date = "11/15/2013";
String newDate = date.substring(0,8)+"00";
Or you can use a StringBuilder:
StringBuilder date = new StringBuilder("11/15/2013");
date.setCharAt(8, '0');
date.setCharAt(9, '0');
or
StringBuilder date = new StringBuilder("11/15/2013");
date.replace(8, 10, "00");
code snippet
String date = "11/15/2013";
String replaced = date.replace("2013","2000");
If you really want to replace a sequence at a certain index of a String, use a StringBuilder:
String replaced = new StringBuilder(date)
.replace(8, 10, "00").toString();
String date = "11/15/2013";
System.out.println(date.substring(0, date.length()-2).concat("00"));
Is this what you are looking for?
Better code snippet
String replaced = date.replace("11/15/2013.","11/15/2000");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For this string, 16.82080560, 96.13055810 I want to get
"String one = 16.82080560"
and
"String two = 96.13055810"
in android.
Admin that I suck in string manipulation and regex.
Please let me know how can I get such two value from a string.
String[] components = original.split(",");
If the Strings are always separated by a comma you can use String.split
For a better regex pattern see the comment from #npinti:
Minor side note, it might be better to do \\s*,\\s* instead of just ,.
Just , might cause problems should the OP wish to cast these to
floats, since the extra white space at the beginning of the second
number will most likely not be recognized as a proper number.
Another option:
String str = "16.82080560, 96.13055810";
StringTokenizer st = new StringTokenizer(str,", ");
String one = st.nextToken();
String two = st.nextToken();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this xml file from where I'm reading this string,
http://localhost:8080/sdpapi/request/10/notes/611/
My question is how can I get just the 611, which is of variable, can be 100000, for example, from this string?
Split the string
String input = "http://localhost:8080/sdpapi/request/10/notes/611/";
String output = input.split("notes/")[1].split("/")[0];
output is the value you need
What language?
Anyway, in most cases it's a syntax like:
String.substring(begin, length);
... where 'begin' is the number of the letter in the string-1. For extracting http from the above string you would write
substring(0, 4);
In case you always need the last string between the last two '/'s, you can retrieve the position of the slashes with index-functions (as stated in the answer of #Liran for example).
// EDIT: In Java the second parameter of substring is not length, but endIndex:
String s = "http://localhost:8080/sdpapi/request/10/notes/611/";
s.substring(46, s.lastIndexOf('/'));
It depends on programming language you use, but Regular Expressions should be the same in most of them:
/(\d+)\/$/
well, it depend in what language are you writing... in c# for example
string s = #"http://localhost:8080/sdpapi/request/10/notes/611/";
s.SubString(s.LastIndexOf('/'));
or
Path.GetFileName(s);
for java
new File(s).getName();