Finding Data within a String - java

I'm trying to find a way to cycle through a string and get data within two characters, for example... I have the following String.
String test = "<172>Lorem Ipsum";
Lets say I want the data that is in-between the two characters '<' & '>'
So the result should be "172"
Now, if the string was going to be 3 digits inbetween these every time, using a sub-string would be fine, however that's not the case, as this string will be changing, so lets say this string could be
String test = "<9>Lorem Ipsum"
I would need the result to be "9"
How should I go about getting this information.

The code will be the following:
String test = "<172>Lorem Ipsum";
int index1 = test.indexOf('<');
int index2 = test.indexOf('>', index1);
String result = test.substring(index1 + 1, index2);
System.out.println("result = " + result);
And the result:
result = 172

String data = test.substring(test.indexOf("<")+1,test.indexOf(">"));

You can use regexp to get the data you need.
Something like this maybe
Pattern p = Pattern.compile("^<(\\d+)>");
Matcher m = p.matcher("<172>Lorem Ipsum");
if (m.find())
System.out.println(m.group(1));
else
System.out.println("your string doesn't start with \"<digits>\"");

In fact for this you can also try using replaceAll with a regex.
System.out.println("<172>Lorem Ipsum".replaceAll(".*<|>.*", ""));

Try something like this:
public Test() {
String test = "<172>Lorem Ipsum";
String number = "";
if (test.startsWith("<")) {
for (int index = 1 ; index < test.length() ; index++) {
if (!test.substring(index, index+1).equals(">")) {
number += test.substring(index, index+1);
} else {
break;
}
}
}
System.out.println(number);
}

int leftBound = data.indexOf("<");
int rightBound = data.indexOf(">");
data.substring(leftBound+1, rightBound));
Figured it out. It was one of those "Ask" then instantly figure it out things.

Related

break large String into small Strings

i have a large string which contains Id's example :
HD47-4585-GG89
here at the above i have an id of a single object but sometimes it may contain id's of multiple objects like this :
HD47-4585-GG89-KO89-9089-RT45
the above haves ids of 2 objects now i want to convert the above string to an array or in multiple small Strings
something like :
id1 = HD47-4585-GG89
id2 = KO89-9089-RT45
every single id haves a fixed number of characters in it here its 14 (counting the symbols too) and the number of total id's in a single String is not determined
i dont know how to do it any one can guide me with this ?
i think all i have to do is clip the first 14 characters of string then assign a variable to it and repeat this until string is empty
You could also use regex:
String input = "HD47-4585-GG89-KO89-9089-RT45";
Pattern id = Pattern.compile("(\\w{4}-\\w{4}-\\w{4})");
Matcher matcher = id.matcher(input);
List<String> ids = new ArrayList<>();
while(matcher.find()) {
ids.add(matcher.group(1));
}
System.out.println(ids); // [HD47-4585-GG89, KO89-9089-RT45]
See Ideone.
Although this assumes that each group of characters (HD47) is 4 long.
Using guava Splitter
class SplitIt
{
public static void main (String[] args) throws java.lang.Exception
{
String idString = "HD47-4585-GG89-KO89-9089-RT45-HD47-4585-GG89";
Iterable<String> result = Splitter
.fixedLength(15)
.trimResults(CharMatcher.inRange('-', '-'))
.split(idString);
String[] parts = Iterables.toArray(result, String.class);
for (String id : parts) {
System.out.println(id);
}
}
}
StringTokenizer st = new StringTokenizer(String,"-");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
these tokens can be stored in some arrays and then using index you can get required data.
String text = "HD47-4585-GG89-KO89-9089-RT45";
String first = "";
String second = "";
List<String> textList = Arrays.asList(text.split("-"));
for (int i = 0; i < textList.size() / 2; i++) {
first += textList.get(i) + "-";
}
for (int i = textList.size() / 2; i < textList.size(); i++) {
second += textList.get(i) + "-";
}
first = first.substring(0, first.length() - 1);
second = second.substring(0, second.length() - 1);

how to replace a word after three slash with another word?

I have one string in which I need to replace one word with another word. Here is my String clientId as /qw/ty/s11/dc3/124 and I have another string id as p13. I want to replace s11 in clientId String with p13.
Format of clientId is going to be exactly same always. Meaning there will be three slah / always after which I need to replace that word with another word so any word after three slashes, I need to replace it with value of id.
String clientId = "/qw/ty/s11/dc3/124";
String id = "p13";
String newId = ""; // this should come as /qw/ty/p13/dc3/124
What is the easy way to do this?
You can definitely change any part of string with help of regex.
Try:
String content = "/qw/ty/xx/dc3/124";
String replacement = "replacement";
Pattern regex = Pattern.compile("((?:/[^/]+){2}/)([^/]*)(\\S*)", Pattern.MULTILINE);
Matcher matcher = regex.matcher(content);
if(matcher.find()){
String result = matcher.replaceFirst("$1" + replacement + "$3");
System.out.println(result);
}
Based on input string and replacement value, it will emit:
/qw/ty/replacement/dc3/124
You can use the indexOf method to search for the second slash. You would have to do that 3 times. And the 3 position returned would be the one you want. Since you are saying the position never changes, that would be a scenario how to do it. Another way would be to split the string with the split method. Then you would have to iterate through it and replace the third word only. And for each iteration you would also have to use StringBuilder to concatenate the String in order to get a path back. Those two approaches would be without using REGEX values. The third option would be, like someone suggested, to use REGEX.
The way I did this problem was by looping through the first string until 3 slashes were found, and setting a variable called "start" to the index of the third slash. Next, I looped through from start until another slash was found, and set a variable called "end" to the index. After that, I used the string replace method to replace the substring from start+1 to end with the new id. Here's the code:
String clientId = "/qw/ty/s11/dc3/124";
String id = "p13";
String newId = "";
String temporaryID = clientId;
int slashCounter = 0;
int start = -1; //Will throw index exception if clientId format is wrong
int end = -1; //Will throw index exception if clientId format is wrong
for(int i = 0; i < temporaryID.length(); i++){
if(temporaryID.charAt(i)=='/') slashCounter++;
if(slashCounter==3){
start = i;
break;
}
}
for(int i = start + 1; i < temporaryID.length(); i++){
if(temporaryID.charAt(i)=='/') end = i;
if(end!=-1) break;
}
newId = temporaryID.replace(temporaryID.substring(start+1, end), id);
System.out.println(newId);
Try this if you need to replace the word between 3rd and 4th slash
int counter = 0;
int start=0;
int end = clientId.length()-1;
for (int i = 0; i < clientId.length(); i++) {
if (clientId.charAt(i) == '/') {
counter++;
if (counter == 3) {
start = i+1; // find the index of the char after the 3rd slash
} else if (counter == 4) {
end = i; // find the index of the 4th slash
break;
}
}
}
String newId = clientId.substring(0, start) + id + clientId.substring(end);
Or if you want to replace everything after the 3rd slash:
String newId = clientId.substring(0, start) + id;
You can try this regex to find string between third and fourth slash which is your ID and do the replace.
Regex: (\/.*?\/.*?\/).*?\/
Regex101 Demo

replacing characters of a string

So I'm trying to iterate over a string and replace ever occurrence of a given substring with a new value. I can't seem to figure out what the problem with my code is because it doesn't seem to make any changes to the strings i run through it.
i create a new string nS that starts out as just “”, and am iterating through the template viewing each character as a substring s. In in every case that something needs to be replaced with a value i append said value on to the nS, else it just appends the current substring as is.
#Override
public String format(String template) {
String nS = "";
for (int i = 0, n = template.length(); i < n; i++) {
String s = template.substring(i, i + 1);
switch (s) {
case "%%":
nS = nS.concat("%");
break;
case "%t":
nS = nS.concat(String.valueOf(inSeconds()));
break;
}
}
return nS;
}
the actual code has many more cases but i left them out so that its not as overwhelming.
The ending index in the 2-arg substring method is exclusive.
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
You are getting a substring of exactly one character, not 2. Try i + 2, after the appropriate bounds-checking:
String s = template.substring(i, i + 2);
Assuming performance is not a big issue I would do
public String format(String template) {
return template.replaceAll ("%%", "\uffff")
.replaceAll("%t", ""+inSeconds())
.replaceAll("\uffff", "%");
}
What you're describing attempting to do sounds like you're trying to rewrite String.replace()
Given String s = "My Name Is Bob"
and you would like to replace "Bob" with "Susan" all you need to do is:
String s = "My Name is Bob";
String n = s.replace("Bob", "Susan");
System.out.println(n); //My Name is Susan
System.out.println(s); //My Name is Bob
Another option, is to break the string into a character array and iterate over it.
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(char c : bits) {
// logic
}
Compare two characters at once:
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(int i = 0; i < bits.length; i++) {
if(i + 1 <= bits.length) {
String searchFor = "" + bits[i] + bits[i + 1];
// logic
}
}

RegEx for dividing complex number String in Java

Looking for a Regular Expression in Java to separate a String that represents complex numbers. A code sample would be great.
The input string will be in the form:
"a+bi"
Example: "300+400i", "4+2i", "5000+324i".
I need to retrieve 300 & 400 from the String.'
I know we can do it crudely in this way.
str.substring(0, str.indexOf('+'));
str.substring(str.indexOf('+')+1,str.indexOf("i"));
I need to retrieve 300 & 400 from the String.
What about using String.split(regex) function:
String s[] = "300-400i".split("[\\Q+-\\Ei]");
System.out.println(s[0]+" "+s[1]); //prints 300 400
Regex that matches this is: /[0-9]{1,}[+-][0-9]{1,}i/
You can use this method:
Pattern complexNumberPattern = Pattern.compile("[0-9]{1,}");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
and use find and group methods on complexNumberMatcher to retrieve numbers from myString
Use this one:
[0-9]{1,}
It'll return the numbers.
Hope it helps.
Regex
([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)\s*\+\s*([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)i
Example Regex
http://rubular.com/r/FfOAt1zk0v
Example Java
string regexPattern =
// Match any float, negative or positive, group it
#"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
// ... possibly following that with whitespace
#"\s*" +
// ... followed by a plus
#"\+" +
// and possibly more whitespace:
#"\s*" +
// Match any other float, and save it
#"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
// ... followed by 'i'
#"i";
Regex regex = new Regex(regexPattern);
Console.WriteLine("Regex used: " + regex);
while (true)
{
Console.WriteLine("Write a number: ");
string imgNumber = Console.ReadLine();
Match match = regex.Match(imgNumber);
double real = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
double img = double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
Console.WriteLine("RealPart={0};Imaginary part={1}", real, img);
}
Try this one. As for me, it works.
public static void main(String[] args) {
String[] attempts = new String[]{"300+400i", "4i+2", "5000-324i", "555", "2i", "+400", "-i"};
for (String s : attempts) {
System.out.println("Parsing\t" + s);
printComplex(s);
}
}
static void printComplex(String in) {
String[] parts = in.split("[+-]");
int re = 0, im = 0, pos = -1;
for (String s : parts) {
if (pos != -1) {
s = in.charAt(pos) + s;
} else {
pos = 0;
if ("".equals(s)) {
continue;
}
}
pos += s.length();
if (s.lastIndexOf('i') == -1) {
if (!"+".equals(s) && !"-".equals(s)) {
re += Integer.parseInt(s);
}
} else {
s = s.replace("i", "");
if ("+".equals(s)) {
im++;
} else if ("-".equals(s)) {
im--;
} else {
im += Integer.parseInt(s);
}
}
}
System.out.println("Re:\t" + re + "\nIm:\t" + im);
}
Output:
Parsing 300+400i
Re: 300
Im: 400
Parsing 4i+2
Re: 2
Im: 4
Parsing 5000-324i
Re: 5000
Im: -324
Parsing 555
Re: 555
Im: 0
Parsing 2i
Re: 0
Im: 2
In theory you could use something like this:
Pattern complexNumberPattern = Pattern.compile("(.*)+(.*)");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
if (complexNumberMatcher.matches()) {
String prePlus = complexNumberMatcher.group(1);
String postPlus = complexNumberMatcher.group(2);
}
The advantage this would give you over selecting the numbers, is that it would allow you to read things like:
5b+17c as 5b and 17c
edit: just noticed you didn't want the letters, so never mind, but this would give you more control over it in case other letters appear in it.

Separate number from a string

I want to get the numbers of a given string and I used the code as below
String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{
if (Character.isDigit(sample.charAt(index)))
{
char aChar = sample.charAt(index);
output = output + aChar;
}
}
System.out.println("output :" + output);
The Result is:
output :7011
Is there any simple way to get the output?
Is there any simple way to get the output
May be you could use a regex \\D+ (D is anything which is not a digit , + means one or more occurence), and then String#replaceAll() all non-digits with empty string:
String sample = "7011WD";
String output = sample.replaceAll("\\D+","");
Though remember, using regex is not efficient at all . Also , this regex will remove the decimal points too !
You need to use Integer#parseInt(output) or Long#parseLong(output) to get the primitive int or long respectively.
You can also use Google's Guava CharMatcher. Specify the range using inRange() and return the characters from that range in sequence as a String using retainFrom().
Also you can use ASCII to do this
String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{
char aChar = sample.charAt(index);
if(int(aChar)>=48 && int(aChar)<= 57)
output = output + aChar;
}
}
System.out.println("output :" + output);

Categories

Resources