I am using String s="abc,def,hi,hello,lol"
By using Java, how we can split the string from the last 3rd comma and get the string and string count?
Need Output as:
,hi,hello,lol
And the count is 13.
Can you please guide me to better code?
Below is my code, but it removes String from the last 3rd comma.
String s ="abc,def,hi,hello,lol";
String[] split = s.split(",");
String newStr = "";
for(int i = 0 ; i < split.length -3 ; i++){
newStr += split[i] + ",";
}
newStr = newStr.substring(0, newStr.length() - 1);
System.out.println(newStr);
Look at String class API.
You can use lastIndexOf(String str, int fromIndex), substring(int beginIndex) and length() methods.
Follow below steps:
Call lastIndexOf 3 times and note down the return value.
Use substring to get string from this index.
Use length to get count.
Try this one,
String data ="abc,def,hi,hello,lol";
StringBuilder sb = new StringBuilder(data);
sb.reverse();
data= sb.toString();
List<String> split = new ArrayList<String>();
int startIndex = 0;
int n = 0;
for (int i = data.indexOf(',') + 1; i > 0; i = data.indexOf(',', i) + 1, n++) {
if (n % 3 == 2) {
split.add(data.substring(startIndex, i ));
startIndex = i;
}
}
split.add(data.substring(startIndex));
for(String s : split)
{
sb = new StringBuilder(s);
s = sb.reverse().toString();
System.out.println(s+" : "+s.length());
}
output :
,hi,hello,lol : 13
abc,def : 7
This one arrives at the answer in only two statements:
public static void main(String[] args) {
String s = "abc,def,hi,hello,lol";
String[] pieces = s.split("(?=,)"); // split using positive lookahead
String answer = (pieces.length < 3) ? "": // check if not enough pieces
Arrays.stream(pieces).skip(pieces.length - 3).collect(Collectors.joining());
System.out.format("Answer = \"%s\"%n", answer);
System.out.format("Count = %d%n", answer.length());
}
I split at the position before each comma using positive lookahead, because if you use a simple split(",") then your program would fail for strings that end with comma.
String output = s.substring(s.indexOf(",", 6));
System.out.println(" string from last 3rd comma -> "+ output +"\n and count -> "+ output.length() );
console output:
string from last 3rd comma -> ,hi,hello,lol and count -> 13
Related
String evensRemoved = "";
String str = reversedNames[1];
String noSpaces = str.replace(" ","");
int strlength = noSpaces.length();
for(int i = 0; i <= strlength; i++){
if(i % 2 == 0){
StringBuilder sb = new StringBuilder(noSpaces);
sb.deleteCharAt(i);
String result = sb.toString();
return result;
}
}
return "";
I want to be able to remove letters at even positions throughout the string completely, and then return the string to the original method. I've looked at other solutions and haven't been able to figure it out at all. New to Java.
Try this.
It uses a regex that takes two chars at a time and replaces them with the 2nd, thus removing every other one.
the (.) is a capture group of 1 character.
$1 is a back reference to it.
String s = "abcdefghijklmnopqrstuvwxyz";
s = s.replaceAll("(?s).(.)?", "$1");
System.out.println(s);
Prints
bdfhjlnprtvxz
per Andreas suggestion, I preceded the regex with a flag that lets . match returns and linefeeds.
To remove all characters at even indexes, copy all the characters at odd indexes to a new char[].
public static String removeEvens(String str) {
char[] buf = new char[str.length() / 2];
for (int i = 0; i < buf.length; i++)
buf[i] = str.charAt(i * 2 + 1);
return new String(buf);
}
Test
String str = "0123456789";
for (int i = 0; i <= str.length(); i++) {
String sub = str.substring(0, i);
System.out.println('"' + sub + "\" -> \"" + removeEvens(sub) + '"');
}
Output
"" -> ""
"0" -> ""
"01" -> "1"
"012" -> "1"
"0123" -> "13"
"01234" -> "13"
"012345" -> "135"
"0123456" -> "135"
"01234567" -> "1357"
"012345678" -> "1357"
"0123456789" -> "13579"
I have:
/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml
But I need only:
/xxx/yyyy
How do I implement this in Java?
Thanks in advance.
You can use StringUtils class for this.
Sample code snippet for your question,
String str = "/xxx/yyy/aaa/bbb/abc.xml";
int index = StringUtils.ordinalIndexOf(str , "/" , 3);
String result = str.substring(0,index);
Or you can use indexOf method iteratively,
String str = "/xxx/yyy/aaa/bbb/abc.xml";
int index = 0 , count = 1;
while(count != 3)
{
index = str.indexOf("/" , index+1);
count++;
}
String result = str.substring(0,index);
You can use String.split("/") for splitting and concat first 2 elements:
for(String string: input){
String[] splitedStrings = string.split("/");
StringBuilder result = new StringBuilder("/");
for(int i = 1; i < 3 && i < splitedStrings.length; i++){
result.append(splitedStrings[i]).append("/");
}
System.out.println("Result: " + result.toString());
}
https://pastebin.com/kpg5VtMk
FilenameUtils.getFullPathNoEndSeparator(str).replaceAll("((/[^/]*){2}).*", "$1")
I used this its working fine for me.
I have a text file which contain many lines, every line contain many words separated by delimiter like "hello,world,I,am,here".
I want to extract some words between position and delimiter for example:
the position is 7 so the string is "world" and if the position was 1 the string will be "hello"
I would recommend using the split() method. With commas delimiting the words you would do this:
String[] words = "hello,world,I,am,here".split(",");
Then you can get the words by position by indexing into the array:
words[3] // would yield "am"
Note that the parameter to split() is a regular expression, so if you aren't familiar with them see the docs here (or google for a tutorial).
Just implement the following code while taking advantage of the method split() that can be used an all Strings objects :
String line = "hello,world,I,am,here";
String[] words = line.split(",");
public static String wordAtPosition(String line, int position) {
String[] words = line.split(",");
int index = 0;
for (String word : words) {
index += word.length();
if (position < index) {
return word;
}
}
return null;
}
Example
String line = "hello,world,I,am,here";
String word = wordAtPosition(line, 7);
System.out.println(word); // prints "world"
First get the substring , then split and get first element from Array.
public class Test {
public static void main(String[] args) throws ParseException {
Test test = new Test();
String t = test.getStringFromLocation("hello,world,I,am,here", 1, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 7, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 6, ",");
System.out.println(t);
}
public String getStringFromLocation(final String input, int position,
String demlimter) {
if (position == 0) {
return null;
}
int absoulutionPosition = position - 1;
String[] value = input.substring(absoulutionPosition).split(demlimter);
return value.length > 0 ? value[0] : null;
}
}
Not the most readable solution but covers corner cases. The split solutions are nice but does not reflect the position in the original string since it skips the ',' from the count
String line = "hello,world,I,am,here";
int position = new Random().nextInt(line.length());
int startOfWord = -1;
int currentComa = line.indexOf(",", 0);
while (currentComa >= 0 && currentComa < position) {
startOfWord = currentComa;
currentComa = line.indexOf(",", currentComa + 1);
}
int endOfWord = line.indexOf(",", position);
if(endOfWord < 0) {
endOfWord = line.length();
}
String word = line.substring(startOfWord + 1, endOfWord);
System.out.println("position " + position + ", word " + word);
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");
I have string like "align is going to school sad may me". I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^ indicates that we remove only from the first character of the string.
\s is any white space. It would also remove, for example, tabulations.
\S is any non white space character.
* means any number of occurrences of the character.
So, \S* is any number of non white space characters before the white space.
{4} is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
This may be a overkill but it uses simple string operations (just str.indexOf(' ')).
If you needed for a school project or someting:
String str ="ada adasd dasdsa d adasdad dasasd";
int targetMatch = 4;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ', offset);
if(position != -1){
System.out.println("position: "+ position);
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
For real project... advanced regex would be better.
Here's a trivial and simple implementation that solves your problem:
String s = "I've tried this one and it's working can you please suggest";
int index = -1;
for (int i = 0; i < 4; i++) {
index = s.indexOf(' ', index + 1);
}
System.out.println(s.substring(index + 1));
It will fail if the string starts with a space or if it contains sequences of spaces. But it's a start.
Output: and it's working can you please suggest
public class MySplit {
public static void main(String agsp[]) {
String oldString = "roma h totti milan kaka juve love";
String[] allStrings = oldString.split("\\s");
String newString = "";
for (int i = 3; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
System.out.println(newString);
}
}
you can also make function like this
public String newSplit(String data, int index){
String[] allStrings = data.split("\\s");
String newString = "";
for (int i = index; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
return newString
}
The simple way using this piece of code
String thisString="Hello world go to kashmir";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
String first = parts[3];//"hello"
String second = parts[4];//"World"