I have string
String path = /mnt/sdcard/Album/album3_137213136.jpg
I want to only strings album3.
How can I get that substring.
I am using substring through index.
Is there any other way because album number is getting changed because it will fail in like album9, album10.
You can use a regular expression, but it seems like using index is the simplest in this case:
int start = path.lastIndexOf('/') + 1;
int end = path.lastIndexOf('_');
String album = path.substring(start, end);
You might want to throw in some error checking in case the formatting assumptions are violated.
Try this
public static void main(String args[]) {
String path = "/mnt/sdcard/Album/album3_137213136.jpg";
String[] subString=path.split("/");
for(String i:subString){
if(i.contains("album")){
System.out.println(i.split("_")[0]);
}
}
}
Obligatory regex solution using String.replaceAll:
String album = path.replaceAll(".*(album\\d+)_.*", "$1");
Use of it:
String path = "/mnt/sdcard/Album/album3_137213136.jpg";
String album = path.replaceAll(".*(album\\d+)_.*", "$1");
System.out.println(album); // prints "album3"
path = "/mnt/sdcard/Album/album21_137213136.jpg";
album = path.replaceAll(".*(album\\d+)_.*", "$1");
System.out.println(album); // prints "album21"
Using Paths:
final String s = Paths.get("/mnt/sdcard/Album/album3_137213136.jpg")
.getFileName().toString();
s.subString(0, s.indexOf('_'));
If you don't have Java 7, you have to resort to File:
final String s = new File("/mnt/sdcard/Album/album3_137213136.jpg").getName();
s.subString(0, s.indexOf('_'));
Use regex to match the substring
path.matches(".*album[0-9]+.*")
Try this ..
String path = /mnt/sdcard/Album/album3_137213136.jpg
path = path.subString(path.lastIndexOf("/")+1,path.indexOf("_"));
System.out.println(path);
How to count substring in String in java
At line no 8 we have to used for loop
another optional case replace for loop using just while loop like as while(true){. . .}
public class SubString {
public static void main(String[] args) {
int count = 0 ;
String string = "hidaya: swap the Ga of Gates with the hidaya: of Bill to make Bites."
+ " The hidaya: of Bill will then be swapped hidaya: with the Ga of Gates to make Gall."
+ " The new hidaya: printed out would be Gall Bites";
for (int i = 0; i < string.length(); i++)
{
int found = string.indexOf("hidaya:", i);//System.out.println(found);
if (found == -1) break;
int start = found + 5;// start of actual name
int end = string.indexOf(":", start);// System.out.println(end);
String subString = string.substring(start, end); //System.out.println(subString);
if(subString != null)
count++;
i = end + 1; //advance i to start the next iteration
}
System.out.println("In given String hidaya Occurred "+count+" time ");
}
}
Related
I have a string format like this which is output of
readAllBytes(new String(Files.readAllBytes(Paths.get(data))
from a file
a+2 b+3 c+33 d+88 ......
My scenario is I want to get the data after c+" ". The position of c is not constant but c occurs only once. It may occur anywhere. My required value will always be after c+ only. The required size of value 33.....is also not constant. Can someone help me with the optimal code please? I think collections need to be used here.
You can use this regex which will let you capture the data you want,
c\+(\d+)
Explanation:
c+ matches a literal c character immediately followed by a + char
(\d+) captures the next digit(s) which you are interested in capturing.
Demo, https://regex101.com/r/jfYUPG/1
Here is a java code for demonstrating same,
public static void main(String args[]) {
String s = "a+2 b+3 c+33 d+88 ";
Pattern p = Pattern.compile("c\\+(\\d+)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("Data: " + m.group(1));
} else {
System.out.println("Input data doesn't match the regex");
}
}
This gives following output,
Data: 33
This code is extracting the value right after c+ up to the next space, or to the end of the string if there is no space:
String str = "a+2 b+3 c+33 d+88 ";
String find = "c+";
int index = str.indexOf(" ", str.indexOf(find) + 2);
if (index == -1)
index = str.length();
String result = str.substring(str.indexOf(find) + 2, index);
System.out.println(result);
prints
33
or in a method:
public static String getValue(String str, String find) {
int index = str.indexOf(find) + 2;
int indexSpace = str.indexOf(" ", index);
if (indexSpace == -1)
indexSpace = str.length();
return str.substring(index, indexSpace);
}
public static void main(String[] args) {
String str = "a+2 b+3 c+33 d+88 ";
String find = "c+";
System.out.println(getValue(str, find));
}
I have a string "abcde-abc-db-tada_x12.12_999ZZZ_121121.333"
The result I want should be 999ZZZ
I have tried using:
private static String getValue(String myString) {
Pattern p = Pattern.compile("_(\\d+)_1");
Matcher m = p.matcher(myString);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
}
else {
System.out.println("not found");
}
}
If you want to continue with a regex based approach, then use the following pattern:
.*_([^_]+)_.*
This will greedily consume up to and including the second to last underscrore. Then it will consume and capture 9999ZZZ.
Code sample:
String name = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
Pattern p = Pattern.compile(".*_([^_]+)_.*");
Matcher m = p.matcher(name);
if (m.matches()) {
System.out.println(m.group(1)); // Should print 999ZZZ
} else {
System.out.println("not found");
}
Demo
Using String.split?
String given = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String [] splitted = given.split("_");
String result = splitted[splitted.length-2];
System.out.println(result);
Apart from split you can use substring as well:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String ss = (s.substring(0,s.lastIndexOf("_"))).substring((s.substring(0,s.lastIndexOf("_"))).lastIndexOf("_")+1);
System.out.println(ss);
OR,
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String arr[] = s.split("_");
System.out.println(arr[arr.length-2]);
The get text between the last two underscore characters, you first need to find the index of the last two underscore characters, which is very easy using lastIndexOf:
String s = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String r = null;
int idx1 = s.lastIndexOf('_');
if (idx1 != -1) {
int idx2 = s.lastIndexOf('_', idx1 - 1);
if (idx2 != -1)
r = s.substring(idx2 + 1, idx1);
}
System.out.println(r); // prints: 999ZZZ
This is faster than any solution using regex, including use of split.
As I misunderstood the logic from the code in question a bit with the first read and in the meantime there appeared some great answers with the use of regular expressions, this is my try with the use of some methods contained in String class (it introduces some variables just to make it more clear to read, it could be written in the shorter way of course) :
String s = "abcde-abc-db-ta__dax12.12_999ZZZ_121121.333";
int indexOfLastUnderscore = s.lastIndexOf("_");
int indexOfOneBeforeLastUnderscore = s.lastIndexOf("_", indexOfLastUnderscore - 1);
if(indexOfLastUnderscore != -1 && indexOfOneBeforeLastUnderscore != -1) {
String sub = s.substring(indexOfOneBeforeLastUnderscore + 1, indexOfLastUnderscore);
System.out.println(sub);
}
I have a requirement to replace all the character within a string to lower case if it is followed by some string like "is".
For example:
String a = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";
it should get converted to
"name=xyz,salaried=Y,address=abc,manager=N,salary=1000"
I am not very good at regular expression but I think can use it to achieve the required output.
It will be great if someone can help me out.
Your solution requires basic understanding of String and String methods in java.
Here is one working example. Although, it might not be the most efficient one.
NOTE:- YOU ASKED FOR A REGEX SOLUTION.BUT THIS IS USING PURE STRING METHODS
public class CheckString{
public static void main(String[] ar){
String s = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";
String[] arr = s.split(",");
String ans = "";
int i = 0;
for(String text : arr){
int index = text.indexOf("=");
String before = text.substring(0,index).replace("is","").toLowerCase();
String after = text.substring(index);
if(i!=(arr.length-1)){
ans += before + after + ",";
i++;
}
else{
ans += before + after;
}
}
System.out.println(ans);
}
}
Try this.
first match the string and replace in a loop
String a = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";
Matcher matcher = Pattern.compile("is(.*?)=").matcher(a);//.matcher(a).replaceAll(m -> m.group(1).toLowerCase());
while (matcher.find()) {
String matchedString = matcher.group(1);
a = a.replace("is"+matchedString,matchedString.toLowerCase());
}
System.out.printf(a);
I have my string defined as
text1:text2:text3:text4:text5
I want to get output as
text1:text2:text3
using String methods.
I have tried using lastIndexOf, then substring and then again lastIndexOf.
I want to avoid these three steps with calling lastIndexOf two times.
Is there a better way to achieve this?
You can do this by running a loop to iterate over the characters of the string from index = 0 to index = lastIndexOf('3'). Here's the code:
String s = "text1:text2:text3:text4:text5";
for(int i = 0; i < = s.lastIndexOf('3'); i++)
System.out.print(s.charAt(i));
This gives you the required output.
OUTPUT:
text1:text2:text3
A regular expression could be used to identify the correct part of the string:
private static Pattern PATTERN = Pattern.compile("([^:]*:){2}[^:]*(?=:|$)");
public static String find(String input) {
Matcher m = PATTERN.matcher(input);
return m.find() ? m.group() : null;
}
Alternatively do not use substring between every call of lastIndexOf, but use the version of lastIndexOf that restricts the index range:
public static String find(String input, int colonCount) {
int lastIndex = input.length();
while (colonCount > 0) {
lastIndex = input.lastIndexOf(':', lastIndex-1);
colonCount--;
}
return lastIndex >= 0 ? input.substring(0, lastIndex) : null;
}
Note that here colonCount is the number of : that are left out of the string.
You could try:
String test = "text1:text2:text3:text4:text5";
String splitted = text.split(":")
String result = "";
for (int i = 0; i <3; i++) {
result += splitted[i] + ":"
}
result = result.substring(0, result.length() -1)
You can use the Java split()-method:
String string = "text1:text2:text3:text4:text5";
String[] text = string.split(":");
String text1 = text[0];
String text2 = text[1];
String text3 = text[2];
And then generate the output directly or with a for-loop:
// directly
System.out.println(text1 + ":" + text2 + ":" + text3);
// for-loop. Just enter, how many elements you want to display.
for(int i = 0; i < 3; i++){
System.out.println(text[i] + " ");
}
Output:
text1 text2 text3
The advantage of using this method is, that your input and output can be a bit more complex, because you have power over the order in which the words can be printed.
Example:
Consider Master Yoda.
He has a strange way of talking and often mixes up the sentence structure. When he introduces himself, he says the (incorrect!) senctence: "Master Yoda my name is".
Now, you want to create an universal translator, that - of course - fixes those mistakes while translating from one species to another.
You take in the input-string and "divide" it into its parts:
String string = "Master:Yoda:my:name:is"
String[] text = string.split(":");
String jediTitle = text[0];
String lastName = text[1];
String posessivePronoun = text[2];
String noun = text[3];
String linkingVerb = text[4];
The array "text" now contains the sentence in the order that you put it in. Now your translator can analyze the structure and correct it:
String correctSentenceStructure = posessivePronoun + " " + noun + " " + linkingVerb + " " + jediTitle + " " + lastName;
System.out.println(correctSentenceStructure);
Output:
"My name is Master Yoda"
A working translator might be another step towards piece in the galaxy.
Maby try this one-line s.substring(0, s.lastIndexOf('3')+1);
Complete example:
package testing.project;
public class Main {
public static void main(String[] args) {
String s = "text1:text2:text3:text4:text5";
System.out.println(s.substring(0, s.lastIndexOf('3')+1));
}
}
Output:
text1:text2:text3
So I have a string that has several start markers and end markers. How can I make a code that only keeps segments that are between the start and end markers?
A good example would be DNA transcription.
So the starting marker would be TAC, and an end marker would be ACT.
I have a string: AGATACACGACTAGCGAGCTACGATACTACC.
I know how to use the substring method, but not well enough so that it cuts the string down to:
TACACGACTTACGATACT.
How can I do this?
EDIT: I have solved this problem by writing this method:
private String spliceString(String n){
int counter1 = 0;
int startloc = 0;
int endloc = 0;
String m = "";
while (n.indexOf("TAC",counter1) != -1){
startloc = n.indexOf("TAC",counter1);
if (n.indexOf("ACT", counter1) != -1){
endloc = n.indexOf("ACT", counter1);
}
else if (n.indexOf("ATT", counter1) != -1){
endloc = n.indexOf("ATT", counter1);
}
else if (n.indexOf("ATC", counter1) != -1){
endloc = n.indexOf("ATC", counter1);
}
else {
return "AAAA"; //Returns a error string. This will be caught in another method that is not relevant.
}
m = m + n.substring(startloc,endloc + 3);
counter1 = endloc + 1;
}
System.out.println(m); //Just prints out so to check if the code worked
return m;
}
For this, regular expression is your friend.
One way would be to search for what you want to keep, and collect that in a StringBuilder.
String input = "AGATACACGACTAGCGAGCTACGATACTACC";
StringBuilder buf = new StringBuilder();
Matcher m = Pattern.compile("TAC.*?ACT").matcher(input);
while (m.find())
buf.append(m.group());
String output = buf.toString();
System.out.println(output); // prints: TACACGACTTACGATACT
See IDEONE for running code.
Read the javadoc of Pattern for more information on regex.
Alternatively, delete what you don't want to keep, i.e.
Text before first TAC
Text between ACT and TAC
Text after last ACT
The code is much simpler, but the regex is a bit more complex:
String input = "AGATACACGACTAGCGAGCTACGATACTACC";
String output = input.replaceAll("(?<=^|ACT).*?(?=TAC|$)", "");
System.out.println(output); // prints: TACACGACTTACGATACT
See regex101.com for nice color-coded example.
Java - String substring() Method
Description:
This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex - 1 If second argument is given.
Syntax:
Here is the syntax of this method:
public String substring(int beginIndex)
or
public String substring(int beginIndex, int endIndex)
Parameters:
Here is the detail of parameters:
beginIndex -- the begin index, inclusive.
endIndex -- the end index, exclusive.
Return Value:
The specified substring.
Example:
import java.io.*;
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.substring(10) );
System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
}
}
This produces the following result:
Return Value : Tutorialspoint.com
Return Value : Tuto