How do I grab each letter of a string in android? - android

I would like to create a small app, and in the app I have the user entering text in an editText. I already know the basics of editText, like how to get the text from it and enter it into a separate string variable. But after I have that string variable, how can I grab each letter of this message separately? I would assume that you need a For loop. Does anyone know of any easy way to do this?

Yes, use can use a For loop like this:
String MyEditText = myEditText.getText().toString();
int len = MyEditText.length();
char chars[] = MyEditText.toCharArray();
for(int i=0;i<len;i++){
//retrieve chars
char newChar = chars[i];
}

for (int i = 0; i < inputString.length(); i++) {
//newChar is equivalent to whatever is at position i
char newChar = inputString.charAt(i); }

Related

How to get counts of characters on every line in TextView?

My TextView has multi-line text. And I want to get counts of characters every single line. I have tried String.split("\n"), but it didn't work...
Try to splite by line using below code
String lines[] = String.split("\\r?\\n");
OR
String lines[] = String.split(System.getProperty("line.separator"));
and If you don’t want empty lines:
String lines[] = String.split("[\\r\\n]+")
Try this:
String[] lines = String.split(System.getProperty("line.separator"));
int[] counts = new int[lines.length];
for(int i = 0; i < lines.length; i++ ){
String line= lines[i].replace(" ", "").trim();
counts[i] = line.toCharArray().length;
}
Then you will get every line's counts of character even you just have one line or empty lines.
You should create a function which store each line in different String variable and then count that string length.

Android: Fill array up to a certain length

The situation
I have got different char[] arrays with a different amount of items. To avoid the "OutOfBounds"-Error while processing them I want to standardize them.
For Example:
My Array has following items: "5;9" --> What I want it to look like: "0,0,0,0,5,9" (fill up with "0"s to 6 items)
What I tried:
char[] myarray1 = mystring1.toCharArray();
...
for(int i=0; i<6; i++){
myarray1[i] = 0;
if(i<myarray1.length-1){
myarray1[i] = myarray1[i];
}else{
myarray1[i] = 0;
};
};
My code failed, because it evokes exactly that error...
I hope somebody can help me :)
Thanks!
The reason why your solution doesn't work is that you are using the same array for everything.
After char[] myarray1 = mystring1.toCharArray(); the length of myarray1 is 2, so you cannot simply assign entry 2,3,4 and 5 in your loop. Furthermore if you want the character ´0´ to be in the string, you need to surround your zeros with apostrophes.
You can fix your solution like this:
char[] myNewArray = new char[6];
int myarrayIndex = 0;
for(int i=0; i<6; i++)
{
if(i < (myNewArray.length - myarray1.length)) {
myNewArray[i] = '0';
} else {
myNewArray[i] = myarray1[myarrayIndex++];
};
};
System.out.println(myNewArray); //Will print out: 000059
An easier solution could be this:
myarray1 = String.format("%6s", mystring1).replace(' ', '0').toCharArray();
Firstly trying to fill 0's is not going to fix the error.
Secondly your logic is not right(assuming size as 6), change it to myString.length().
And I don't understand the point of myarray1[i] = myarray1[i];.
Anyways, every array with integer size is initialized by Zero's according to Java specs. On the other hand if you want to fill it with any other value, try Arrays.fill().
I think this function will accomplish what you're trying to do.
private static String formatString(String input)
{
String FORMATTED_STRING = "0,0,0,0,0,0";
int difference = FORMATTED_STRING.length() - input.length();
return FORMATTED_STRING.substring(0, difference) + input;
}

How to convert a string to character by character in Android?

I have Edittext field that the user can enter their name. I want to check it with alphabets for how many times a letter comes.
Which is the best way to do this?
I tried the below code for getting each character from the string but error occurring? I appreciate it if any one can help.
name=(EditText)findViewById(gami.Numerology.R.id.inputUI);
String a=name.getText().toString();
for ( int i = 0; i < a.length(); i++ )
{
c = a.charAt(i);
if (c=='s')
{
s=1; //like this for all characters
}
}
I just put this in a click event of button.
//declare the original String object
String strOrig = "Hello World";
//declare the char array
char[] stringArray;
//convert string into array using toCharArray() method of string class
stringArray = strOrig.toCharArray();
//display the array
for(int index=0; index < stringArray.length; index++)
//check of character appearance
You can use a hashmap or some sort of dictionary in Java.
Rough example since I don't know how to use Hashmap in Java:
HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
for (Character c: name)
{
counter.put(c, counter.get(c) == null ? 1 : counter.get(c)++);
}

HTML.fromHtml line breaks disappearing

I am taking Spanned Text from an EditText box and converting it to a HTML tagged string using HTML.toHtml. This works fine. I have verified that the string is correct and contains a <br> in the appropriate location. However, when I got to convert the tagged string back to a spanned text to populate a TextView or EditText using HTML.fromHtml the <br> (or multiple ones if they are present) at the end of the first paragraph disappear. This means that if a users entered text with multiple line breaks and wanted to keep that formatting it gets lost.
I attached a picture to help illustrate this. The first EditText is the user input, the TextView Below it is the HTML.tohtml result of the EditText above it, the EditText below it is populated using HTML.fromHtml using the string in the TextView above it. As you can see the line breaks have disappeared and so have the extra lines. Furthermore, when the spanned text of the second edit text is run through the HTML.toHtml it now produces a different HTML tagged String.
I would like to be able to take the HTML tagged String from the first EditText and populate other TextViews or EditTexts without losing line breaks and formatting.
I also had this problem and I could not find an easy "transform" or something alike solution. Note something important, when the user presses "enter" java produces the special character \n but in HTML there is no such format for line breaking. It is the <br />.
So what I have done was to replace some specific CharSequences, from the plain text, by the alternative HTML format. In my case there was only the "enter" character so it was not that messy.
I had similar problem when I was trying to save/restore editText content to db. The problem is in Html.toHtml, it somehow skips line brakes:
String src = "<p dir=\"ltr\">First line</p><p dir=\"ltr\">Second<br/><br/><br/></p><p dir=\"ltr\">Third</p>";
EditText editText = new EditText(getContext());
// All line brakes are correct after this
editText.setText(new SpannedString(Html.fromHtml(src)));
String result = Html.toHtml(editText.getText()); // Here breaks are lost
// Output :<p dir="ltr">First line</p><p dir="ltr">Second<br></p><p dir="ltr">Third</p>
I've solved this by using custom toHtml function to serialize spanned text, and replaced all '\n' with "< br/>:
public class HtmlParser {
public static String toHtml(Spannable text) {
final SpannableStringBuilder ssBuilder = new SpannableStringBuilder(text);
int start, end;
// Replace Style spans with <b></b> or <i></i>
StyleSpan[] styleSpans = ssBuilder.getSpans(0, text.length(), StyleSpan.class);
for (int i = styleSpans.length - 1; i >= 0; i--) {
StyleSpan span = styleSpans[i];
start = ssBuilder.getSpanStart(span);
end = ssBuilder.getSpanEnd(span);
ssBuilder.removeSpan(span);
if (span.getStyle() == Typeface.BOLD) {
ssBuilder.insert(start, "<b>");
ssBuilder.insert(end + 3, "</b>");
} else if (span.getStyle() == Typeface.ITALIC) {
ssBuilder.insert(start, "<i>");
ssBuilder.insert(end + 3, "</i>");
}
}
// Replace underline spans with <u></u>
UnderlineSpan[] underSpans = ssBuilder.getSpans(0, ssBuilder.length(), UnderlineSpan.class);
for (int i = underSpans.length - 1; i >= 0; i--) {
UnderlineSpan span = underSpans[i];
start = ssBuilder.getSpanStart(span);
end = ssBuilder.getSpanEnd(span);
ssBuilder.removeSpan(span);
ssBuilder.insert(start, "<u>");
ssBuilder.insert(end + 3, "</u>");
}
replace(ssBuilder, '\n', "<br/>");
return ssBuilder.toString();
}
private static void replace(SpannableStringBuilder b, char oldChar, String newStr) {
for (int i = b.length() - 1; i >= 0; i--) {
if (b.charAt(i) == oldChar) {
b.replace(i, i + 1, newStr);
}
}
}
}
Also it turned out that this way is faster in about 4 times that default Html.toHtml(): I've made a benchmark with about 20 pages and 200 spans:
Editable ed = editText.getText(); // Here is a Tao Te Ching :)
String result = "";
DebugHelper.startMeasure("Custom");
for (int i = 0; i < 10; i++) {
result = HtmlParserHelper.toHtml(ed);
}
DebugHelper.stopMeasure("Custom"); // 19 ms
DebugHelper.startMeasure("Def");
for (int i = 0; i < 10; i++) {
result = Html.toHtml(ed);
}
DebugHelper.stopMeasure("Def"); // 85 ms
Replace /n => < br>< br>
example
< p>hi< /p>
< p>j< /p>
to:
< p>hi< /p>< br>< br>< p>j< /p>

Android how to print a array in text view or anything

I have a array of words and I would like to print the array of words onto the screen in a text view after a button is clicked. i was using a for loop to go through the whole list and then set text, but i keep getting a error with that plus it will just replace the last value, so it wont print the whole array. If anybody could explain to me how to do like a g.drawSting() but android version that would be great. my code rt now is not with me but it something like:
-I'm a beginner to android btw, probably could tell by this question tho.
public void onCreate(Bundle savedInstanceState)
{
//code for a button just being pressed{
//goes to two methods to fix the private array{
for(int y=0; y<=array.size()-1; y++){
textArea.setText(aarray.get(y)); //prints all strings in the array
}
}
}
int arraySize = myArray.size();
for(int i = 0; i < arraySize; i++) {
myTextView.append(myArray[i]);
}
if you want to print one by one, then use \n
myTextView.append(myArray[i]);
myTextView.append("\n");
PS:
Whoever suggesting to change .size() to .length(), thanks for you suggestion.
FYI,
The questioner mentioned the variable name is array.size() in question, so the answer also having the same variable name, to make it easier for the questioner.
if your variable (myArray) is an Array use myArray.length(), if it is ArrayList use myArray.size()
You have to combine all text into a String before you can give it the TextView. Otherwise you overwrite the text all the time.
public void onCreate(Bundle savedInstanceState)
{
StringBuilder sb = new StringBuilder();
int size = array.size();
boolean appendSeparator = false;
for(int y=0; y < size; y++){
if (appendSeparator)
sb.append(','); // a comma
appendSeparator = true;
sb.append(array.get(y));
}
textArea.setText(sb.toString());
}
I use this no-index solution, just an easy to remember one liner:
for(File file:list) Log.d(TAG, "list: " + file.getPath());

Categories

Resources