Android: How to set substrings in lowercase in my string? - android

I want to set all my hashtags in lowercase in a string:
"Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp"
Should become:
"Hello I'm a men #athlete et I'm going to
do sport #nevergiveup"

if your problem is how to convert all to simple letters hope this helps
String myString = "HashTag";
String myNewSimpleLetterString = myString.substring(0,5).toLowerCase(); //subString will get the characters from 0 - 5

Try this code
Just pass your string to this method this method returns formatted String
public static String changeFormat(String beforeFormatStr) {
String[] arrStr = beforeFormatStr.split(" ");
String afterFormatStr = "";
int wordPos = 0;
for (String word : arrStr) {
String changeStr = word;
if (word.contains("#")) {
changeStr = word.toLowerCase();
}
if (wordPos == 0) {
afterFormatStr += changeStr;
} else {
afterFormatStr += " " + changeStr;
}
wordPos++;
}
return afterFormatStr;
}

You can use Regular expression for finding and replacing hashtags to lowercase. Like :
String line = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp";
String regEx = "\\S*#(?:\\[[^\\]]+\\]|\\S+)"; //Regular expression for matching hashtag
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(line);
while (m.find())
{
// Avoids throwing a NullPointerException in the case that you
// Don't have a replacement defined in the map for the match
String repString = m.group();
if (repString != null)
repString = repString.toLowerCase();
m.appendReplacement(sb, repString);
}
m.appendTail(sb);
String replacedHashtag = sb.toString();

Hash is not a string, so you have to use Regx matcher and Pattern to achieve this.
List<String> obtained_hashwords = new ArrayList<>();
String text_data = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp and I want to format this string";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text_data);
while (matcher.find())
{
obtained_hashwords.add(matcher.group());
Log.d("Hash word",matcher.group());
}
for (String obtained_hashword:obtained_hashwords)
{
String no_hash = obtained_hashword.replace("#","");
String lower_case_word = "#"+no_hash.toLowerCase();
text_data = text_data.replace(obtained_hashword,lower_case_word);
}
Log.d("changed line",text_data);

Related

How to create a string / string array from a .txt/.xml file?

I know it has been asked a million times, but I just can't find anything that Works, and I just started learning to code
I'm trying to use regex to tell when the user types any of 118 different patterns, so you can guess it'd be a really long string, and I have all the patterns in a .txt/.xml file and I want to create a string or array with these patterns
The code:
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private EditText et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
et3 = (EditText)findViewById(R.id.et3);
}
public void boton (View view){
String text = et3.getText().toString();
//String[] symbolsArr = {"He|","H|","Os|","O"};
//StringBuffer sb = new StringBuffer();
//for(int i = 0; i < symbolsArr.length; i++) { //all of this is just to convert an array to a single string
// sb.append(symbolsArr[i]);
//
String symbols = "Zr|Zn|Yb|Y|Xe|W|V|U|Ts|Tm|Tl|Ti|Th|Te|Tc|Tb|Ta|Sr|Sn|Sm|Si|Sg|Se|Sc|Sb|S|Ru|Rn|Rh|Rg|Rf|Re|Rb|Ra|Pu|Pt|Pr|Po|Pm|Pd|Pb|Pa|P|Os|Og|O|Np|No|Ni|Nh|Ne|Nd|Nb|Na|N|Mt|Mo|Mn|Mg|Md|Mc|Lv|Lu|Lr|Li|La|Kr|K|Ir|In|I|Hs|Ho|Hg|Hf|He|H|Ge|Gd|Ga|Fr|Fm|Fl|Fe|F|Eu|Es|Er|Dy|Ds|Db|Cu|Cs|Cr|Co|Cn|Cm|Cl|Cf|Ce|Cd|Ca|C|Br|Bk|Bi|Bh|Be|Ba|B|Au|At|As|Ar|Am|Al|Ag|Ac";
//The really long string with all the patterns
Pattern p = Pattern.compile(symbols);
Matcher m = p.matcher(text);
tv1.setText("");
while (m.find()){
tv1.append("found " + m.group() + "\n");
}
}
}
It depends of how do you want to storage the file.
For example let`s use assets.
Put file data.txt in assets(you can create this in File/New/Folder/Assets Folder)
After that you can create method, wich help you to get string from assetFile
public String getStringFromAssetFile(Context context, String nameFile)
{
String str = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(nameFile)));
String line;
while ((line = reader.readLine()) != null) {
str += line;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return str;
}
Now you can use this method to create a string or array with these patterns
String symbols = getStringFromAssetFile(MainActivity.this, "data.txt");

Problems splitting string at first empty space

I have a string which i need to split at the first empty space.
Somehow I can not get it to split, the string stays untouched.
Could somebody help?
String in question:
https://test.com/info/dsfs76/933/TT Maps 2015.12
https://test.com/info/dsfs76/933/TT and Maps 2015.12 need to be 2 seperate parts which are added to an arraylist.
My code attempt:
if (str.contains(linkElem.getLinkAddress() + " ")) {
String[] temp = str.split(" ");
for (String temp : Arrays.asList(temp)) {
arraytest.add(temp);
}
}
From the code you provided, there is no such String strtemp
Maybe you should be splitting str instead?
String[] temp = str.split(" ");
You can use String tokenizer to do that like this:
StringTokenizer st = new StringTokenizer(linkElem.getLinkAddress(), " ");
String a = st.nextToken();//string before " "
String b = st.nextToken();//string after " "
i know it is completely unelegant and dumb but it works %)
String string = "https://test.com/info/dsfs76/933/TT Maps 2015.12";
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> list = new ArrayList<>();
boolean whiteSpaceFound = false;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == ' ' && !whiteSpaceFound) {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
whiteSpaceFound = true;
} else {
stringBuilder.append(string.charAt(i));
}
}
if (whiteSpaceFound || list.isEmpty()) {
list.add(stringBuilder.toString());
}

Assign Integer Value to String

I am developing an app in which i have to assign integer values to different string of words. For Example I want to assign:
John = 2
Good = 3
Person= 7
Now these John, Good and person are strings while 2,3 and 7 are int values. But I am so confused about how to implement that. I read many things about how to convert int to string and string to int but this is different case.
I am giving option to user to enter a text in editText and if for example User enters "Hello John you are a good person" then this line output will be 12 as all the three words John, Good and person are there in the input text. Can you tell me how to achieve that?
I am stuck here is my little code:
String s = "John";
int s_value= 2;
now I want to assign this 2 to John so that whenever user give input and it contains John then the value 2 is shown for John. Please Help as I am just a beginner level programmer
Here is my code (Edited)
String input = "John good person Man";
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
//int number = map.get("Good");
String[] words = input.split(" ");
ArrayList<String> wordsList = new ArrayList<String>();
for(String word : words)
{
wordsList.add(word);
}
for (int ii = 0; ii < wordsList.size(); ii++) {
// get the item as string
for (int j = 0; j < stopwords.length; j++) {
if (wordsList.contains(stopwords[j])) {
wordsList.remove(stopwords[j]);//remove it
}
}
}
for (String str : wordsList) {
Log.e("msg", str + " ");
}
As u see i applied code of you and then i want to split my main string so that each word of that string compares with the strings that are in the Map<>. Now i am confused what to write in the for loop ( 'stopwords' will be replaced by what thing?)
You can use a Map<String, Integer> to map words to numbers:
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
and then query the number given a word:
int number = map.get("John"); // will return 2
UPDATE
The following code iterates over a collection of words and adds up the values that the words match to:
List<String> words = getWords();
int total = 0;
for (String word : words) {
Integer value = map.get(word);
if (value != null) {
total += value;
}
}
return total;
I would use a Dictionary for this. You can add a string and an int (or anything else actually) value for that string.
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("John", 2);
d.Add("Good", 3);
d.Add("Person", 7);
You can use String contains to achieve this. Following is the code:
String input = "John you are a good person";
String s1 = "John";
String s2 = "good";
String s3 = "person";
int totScore =0;
if(input.contains(s1)) {
totScore=totScore+2;
}
else if (input.contains(s2)) {
totScore=totScore+3;
}
else if (input.contains(s3)) {
totScore=totScore+7;
}
System.out.print(totScore);
You can use class like.
class Word{
String wordName;
int value;
public Word(String wordName, int value){
this.wordName = wordName;
this.value = value;
}
// getter
public String getWordName(){
return this.wordName;
}
public int getValue(){
return this.value;
}
// setter
public void setWordName(String wordName){
this.wordName = wordName;
}
public void zetValue(int value){
this.value = value;
}
}
You can create an object of the word
Word person = new Word("Person",3);

create array of keys from an object Android

I'm wanting to create an array of all keys within an object does anyone know how to do this in Android? in iOS I have done this
NSDictionary *variablesDictionary = [[NSDictionary alloc] init];
// ^^ full of variables and keys...
NSString *finalString = #"";
if(variablesDictionary != nil){
NSArray *keysArray = [variablesDictionary allKeys];
for(NSString *singleKey in keysArray) {
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:#"&%#=%#", singleKey, [variablesDictionary objectForKey:singleKey]]];
}
}
//final string will = '&key=variable&key=variable&key=variable&key=variable' etc...
heres what i have tried so far. heres my global actions
public final static void startAPICallRequest(Context activityContext, String request, String apiLocation, Object postVarsObj, Object getVarsObj){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
if(getVarsObj != null){
Array keysArray = getVarsObj.keySet().toArray();
StringBuilder sb = new StringBuilder();
for (String key : getVarsObj.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(getVarsObj.get(key).toString());
}
final String will = sb.toString();
}
}
// for Map<String, Object>
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(map.get(key).toString());
}
final String will = sb.toString();
If using a map, you'll want to take a look at the keySet() functionality. Here is an example

Remove string from string

String startTag = "<sessionid>";
String endTag = "</sessionid>";
if (startTag.equalsIgnoreCase("<sessionid>") &&
endTag.equalsIgnoreCase("</sessionid>"))
{
int startLocation = strResponse.indexOf(startTag);
int endLocation = strResponse.indexOf(endTag);
Log.i("StartLocation", ""+startLocation);
Log.i("EndLocation", ""+endLocation);
String session_id = strResponse.substring(startLocation, endLocation);
ConstantData.session_id =session_id;
Log.i("SessionId", ""+session_id);
}
I am getting session_id = <sessionid>32423jhoijhoijh; so I want to remove <sessionid>. Any help will be appreciated.
int startLocation = strResponse.indexOf(startTag) + string length of startTag
Just remove the first 11 letters or characters from the String:
String startTag = "<sessionid>";
String endTag = "</sessionid>";
if (startTag.equalsIgnoreCase("<sessionid>") &&
endTag.equalsIgnoreCase("</sessionid>"))
{
int startLocation = strResponse.indexOf(startTag);
int endLocation = strResponse.indexOf(endTag);
Log.i("StartLocation", ""+startLocation);
Log.i("EndLocation", ""+endLocation);
String session_id = strResponse.substring(startLocation, endLocation);
session_id = session_id.substring(11, session_id.length());
ConstantData.session_id =session_id;
Log.i("SessionId", ""+session_id);
}
Take the length of "<sessionid>" as your startIndex instead of indexOf.
One might try regular expressions too;
String str = "<sessionid>ABCDEFGH</sessionid>";
str = str.replaceFirst("<sessionid>(\\S+)</sessionid>", "$1");

Categories

Resources