How to replace character at particular index in android? - android

I am working on android. I have a string containing huge data. In that string I want to replace a particular character to another character. I got the index of the character which I want to replace. But I am unable to replace that character.
How can I do that?
String str = "data1data2mdata2test1test2test3dd"
int ind = str.indexOf("m");
System.out.println("the index of m" + ind);
Now in the above string I want to replace the character "m"(after data2) to "#".
Now how can I replace the m to #. Please help me in this reagard.

You can use substring:
String newStr = str.substring(0, ind) + '#' + str.substring(ind + 1);

Try this:
str = str.replaceFirst("m", "#");
It will replace the first m to #

String str1 = "data1data2mdata2test1test2test3dd"
String str = str1.replace("m", "#");
System.out.println(str);

So you are getting 10 as system out,
so this way you can replace it like,
Str.replace('m', '#')--->when you want all occurrences of it to replace it,
Or if you want only first occurrence to be replaced by # then you can do following trick,
StringBuffer buff=new StringBuffer();
buff.append(Str.substring(0,ind)).append("#").append(Str.substring(ind+1));
i hope it would help

Related

how to remove special character from string except + in android?

I am fetching number from contact book and sending it to server. i get number like this (+91)942 80-60 135 but i want result like this +9428060135.+ must be first character of string number.
Given your example you want to replace the prefix with a single + character. You also want to remove other non-numeric characters from the number string. Here's how you can do that:
String number = "(+91)942 80-60 135";
number = "+" + number.replaceAll("\\(\\+\\d+\\)|[^\\d]", "");
The regex matches any prefix (left paren followed by a + followed by one or more digits, followed by a right paren) or any non digit character, and removes them. This is concatenated to a leading + as required. This code will also handle + characters within the number string, e.g. +9428060135+++ and +(+91)9428060135+++.
If you simply wanted to remove any character that is not a digit nor a +, the code would be:
String number = "(+91)942 80-60 135";
number = number.replaceAll("[^\\d+]", "");
but be aware that this will retain the digits in the prefix, which is not the same as your example.
You can use String.replace(oldChar, newChar). Use the code below
String phone = "(+91)942 80-60 135"; // fetched string
String trimmedPhone = phone.replace("(","").replace(")","").replace("-","").trim();
I hope it will work for you.
check this. Pass your string to this function or use as per code goes
String inputString = "(+91)942 80-60 135";
public void removeSpecialCharacter(String inputString) {
String replaced = inputString.replaceAll("[(\\-)]", "");
String finalString = replaced.replaceAll(" ", "");
Log.e("String Output", " " + replaced + " " + second);
}

what is the characters behind the characters down the line?

I am converting between "\n" to ":" in file .txt. And here, this is my paragraph before convert:
You can see that, between string "Hoa" and string "Đàm", it have one character " " and two character "\n". And this is my convert function:
private String convertData(){
String different = "~`!##$%^&*()-_=+*/\\\"'|]}{[:;?/.><,\n ";
StringBuilder data = new StringBuilder(tvData.getText().toString().trim());
for (int j = 0; j < data.length(); j++){
if(different.contains("" + data.charAt(j))) data.setCharAt(j, ':');
}
String convertData = data.toString().trim();
return convertData;
}
And this is result:
You can see behind character "\n" have a character, and it is not in string different.
Can anyone tell me what to do?
1 - Proceed like you're currently doing, but the \n (and the other escaped sequences).
So, use
String different = "~`!##$%^&*()-_=+*/'|]}{[:;?/.><, ";
2 - After the loop, use string.replace() to replace only the substring "\n" and the other sequences, i.e.: "\\" and "\"".
You could use a loop to replace the sequences, but you must replace 2 characters instead of one.
Basically, in the first loop you replace all the single characters.
Then, you replace the character sequences.
Notepad only supports Windows line endings (\r\n), so that must be what your file contains. Convert the file to Unix line endings (\n) using literally any program that is not Notepad, or add \r to your search pattern.

Android - how to read first line of the string

i have string with \n, i would like to read first line of the string. i have tried following but its giving error.
String lines[] = plain.split("\\r?\\n");
String a = String.parse(lines[0]);
String b = String.parse(lines[1]);
in same time if someone tells me how to replace first line data with another value would be great.
my data is as follows
123456
A B C D
p o s j s u w
Thanks
I think you mean to only put \n and \r using double back slash will give you a literal \n
"\\n" = \n
"\n" = newline
I'm also not sure about your ? in the line
I think you want something like this (depending on the type of line endings):
String[] lines = plain.Split(new string[] {"\r\n", "\n", "\r" },StringSplitOptions.None);
After that you should probably step through your string array using for each or similar, not just assume that a you will have a [0] and [1] in the array.
However assuming you do have two lines accessing them will be
a = lines[0];
b = lines[1];
replacing a value would be
a = lines[0].replace("stuff","things");
Hope fully this will help yours..
import java.util.Arrays;
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String data = "123456\n"
+ "\n"
+ "A B C D\n"
+ "\n"
+ "p o s j s u w\n"
+ "\n"
+ "Thanks";
String[] lines = data.split("\\n");
System.out.println("Before "+Arrays.toString(lines));
lines[0]=lines[0].replace("123456","ABCD PUUJA");
System.out.println("After "+Arrays.toString(lines));
}
}
To read a line we use:
String myline = reader.readLine()
Now in your case we can use the follwoing code to read the first line however We will not use "\n" but we will look for another character like "&", "$" or even "#" and use it as below:
String mytext = "This is my code.$ I want to read the first line here.$ Please check it out";
thetext = mytext .replace("$", System.getProperty("line.separator"));
String[] strings = TextUtils.split(mytext, "$");
String a = strings[0].trim();
String b = strings[1].trim();
String a is the first line while String b is the second line
In case you use Kotlin, you can use lines() method
val myString = "Hello \n NewLine"
myString.lines() // this will give you a List<String> type

how to get text with using substring

I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).

How do I match the pattern in android

I am currently working on an android project. I would like to know if a string contains the '\r' or '\n' as the last character. How to do the pattern match?
Try this.
String string = "stackoverflow";
lastchar = string.substring(string.length() - 1);
It will give you the result "w".
try
String patterntomatch ="^[_A-Za-z0-9-]*(\r\n)$";
Pattern pattern=Pattern.compile(patterntomatch);
Matcher matcher=pattern.matcher(matchfromedittext);
boolean matcher.matches();
String last = your_string.substring(Math.max(your_string.length() - 2, 0));
//It will give you the last 2 characters of the string. If the string is null
//or has less than 2 characters, then it gives you the original string.
if(last.equals("\r") || last.equals("\n")){
//String's last two characters are either \n or \r. Now do something.
}

Categories

Resources