Cannot convert int to String - android

This doesn't work:
int number = 1;
String numberstring = IntToString(number);
I get "The method IntToString(int) is undefined for the type (myclassname)"
I must be tired here. What the heck am I forgetting?

Try this.
int number = 1;
String numberstring = Integer.toString(number);

You can do either:
String numberstring = number.toString();
or
String numberstring = Integer.toString(number)
or (as a tricky thing sometimes I do this)
String numberstring = 1 + "";

Why not this :
int number = 1;
String numberstring = number+"";
Also make sure that :
Is there IntToString method in your class file - myclassname? Is the arguement types are matching?

These ones are the ones that seems to work "out of the box", without importing any special classes:
String numberstring = String.valueOf(number);
String numberstring = Integer.toString(number);
String numberstring = number + "";

One way to do this with very little code would be like this:
int number = 1;
String numberstring = number + "";

Are you expecting this -
int numb = 1;
String val = String.valueOf(numb);

int number=1;
String S = String.valueOf(number);
try this code... works for me :)

In Java, int to String is simple as
String numberstring = String.valueOf(number);
This applies to Android too.

Related

Split datetime from string android

I have String s = http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/
(Using Java android)how to split date string 23-4-2015 from it become two substring:
http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
23-4-2015
Use the substring method
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
url = str.substring(0, 43);
date = str.substring(44, 53);
I hope the date will always be on the last. So you can actualy do Java substring take the last 11 char from the end. Because there is "/".
Hard way you can actually do a RegEx to get only a number. But it is not possible if in the URL there is a numerical too.
Try this using regular expressions,
String str = "http://kqxs.net.vn/xo-so-ngay/an-giang-xsag-23-4-2015/";
String regexStr = "\\d{2}-\\d{1,2}-\\d{4}";
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(str);
int startIndex=-1;
// Check all occurrences
while (matcher.find()) {
startIndex = matcher.start();
}
if(startIndex>0){
String firstPart = str.substring(0,startIndex-1);
String secondPart = str.substring(startIndex);
System.out.println("First Part "+firstPart);
System.out.println("Second Part "+secondPart);
}else{
System.out.println("Match Not Found!");
}
Output:-
First Part http://kqxs.net.vn/xo-so-ngay/an-giang-xsag
Second Part 23-4-2015/
Try This code for The Get the date from the String.
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
Try this another code
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

Implement Regular expression in android

I got stuck in this regular expression as I am having a string as:
String str = "/abcde/samplename.xyz"
I want to replace this samplename.xyz from a new string, so how can I apply the regular expression in this ?
Try this out.....
String str = "/abcde/samplename.xyz";
String req=str.substring(str.lastIndexOf("/") + 1);
now you get the value of: req=samplename.xyz and you can replace with which ever string value you want
String rep=str.replace(req, "");
String startString=str.substring(0, str.lastIndexOf('/') + 1)
String str = "/abcde/samplename.xyz";
String str1 = str.substring(0, str.lastIndexOf('/') + 1);
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
Log.i("strArr[1]=", "" + str1);
check this.i hope its useful to you.
Try this::
String str = "/abcde/samplename.xyz";
String result=str.substring(0, str.lastIndexOf('/') + 1);
Log.d("Hello","Result="+result);
String[] result = str.split("/");
String LastItem = result[str.length -1];
LastItem.replace(newString);

int to String in Android

I get the id of resource like so:
int test = (context.getResourceId("raw.testc3"));
I want to get it's id and put it into a string. How can I do this? .toString does not work.
String testString = Integer.toString(test);
Or you can use Use
String.valueOf()
eg.
int test=5;
String testString = String.valueOf(test);
Very fast to do it if you dnt remember or dnt have time to type long text :
int a= 100;
String s = ""+a;
What about:
int a = 100;
String s = String.format("%d", a);

Extract substring from a string

what is the best way to extract a substring from a string in android?
If you know the Start and End index, you can use
String substr=mysourcestring.substring(startIndex,endIndex);
If you want to get substring from specific index till end you can use :
String substr=mysourcestring.substring(startIndex);
If you want to get substring from specific character till end you can use :
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));
If you want to get substring from after a specific character, add that number to .indexOf(char):
String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);
substring():
str.substring(startIndex, endIndex);
Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h
There is another way , if you want to get sub string before and after a character
String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
check this post-
how to find before and after sub-string in a string
substring(int startIndex, int endIndex)
If you don't specify endIndex, the method will return all the
characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Example:
String str = "abcdefgh"
str.substring(0, 4) => abcd
str.substring(4, 6) => ef
str.substring(6) => gh
you can use this code
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
Log.d("message", "" + mainString.substring(startIndex, endIndex));
endString = mainString.substring(startIndex, endIndex);
return endString;
}
in this mainString is a Super string.like
"I_AmANDROID.Devloper"
and lastString is a string like"." and startString is like"_".
so this function returns "AmANDROID".
enjoy your code time.:)
use text untold class from android: TextUtils.substring (charsequence source, int start, int end)
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
When finding multiple occurrences of a substring matching a pattern
String input_string = "foo/adsfasdf/adf/bar/erqwer/";
String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input_string);
while(matcher.find()) {
String str_matched = input_string.substring(matcher.start(), matcher.end());
// Do something with a match found
}
The best way to get substring in Android is using (as #user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:
public String substring(int start) {
if (start == 0) {
return this;
}
if (start >= 0 && start <= count) {
return new String(offset + start, count - start, value);
}
throw indexAndLength(start);
}
Ok, than... How do you think the private constructor String(int, int, char[]) looks like?
String(int offset, int charCount, char[] chars) {
this.value = chars;
this.offset = offset;
this.count = charCount;
}
As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.
In the newest Java it was fixed:
String(int offset, int charCount, char[] chars) {
this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
this.offset = offset;
this.count = charCount;
}
Arrays.copyOfRange(...) uses native array copying inside.
That's it :)
Best regards!
All of The responders gave good answers. However, I am giving you all relatable methods for this so that any one can get from one place, I'll edit my answer if I find something new.
substring(0)- use for cut string from given specific char.
Substring(0,2)- give you sub string from starting(0) and ending(2) characters.
Split("NAME")- return you string in two parts first is that you use in split "NAME" and another part is rest of string combine.
subSequence(0,3) - returns sequence of give start(0) and ending index(3).
This one is not specifically use for split string but though it may be use full for some one
startswith("A",3)- returns string for specific starting character.
For example:
String s = "StackOverflow";
String[] split = s.split("Stack");
System.out.println("STRING NAME:"+s.substring(2));
System.out.println("STRING NAME:"+s.substring(2,3));
System.out.println("STRING NAME:"+split[1]);
System.out.println("STRING NAME:"+split[0]);
System.out.println("STRING NAME:"+s.subSequence(2,5));
Output:
1)ackOverflow
2)a
3)Overflow
4)stack
5)ack
I hope this will give you enough information that you require.

Categories

Resources