Hi any Body give me an idea how to convert a number to word.
For exm:- if number is 100 the word must be one hundred.
if number is 250 then word will be two hundred fifty etc.
If i give any input of a number then the corresponding word of out will be print in console.
Thanks
jay
-(NSString*)numberToWord:(NSInteger)number {
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
return [formatter stringFromNumber:[NSNumber numberWithInteger:number]];
}
I've made a Java program that converts any Integer type number (byte, short, int and even long !) into words.
This value goes into pentillions
One pentillion = 1000000 trillion
both in negative and positive, including zero.
Here you go :
package Practice.Program;
public class Num2Words {
private static long number;
private static String words = new String("");
public Num2Words(long n){ number = n; }
static String[] tp = {"", "thousand ", "million ", "billion ", "trillion ", "quadrillion ", "pentillion "};
static String[] od = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
static String[] td = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
static String[] tn = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
public String toWords(){
words = Long.toString(number);
int l = words.length();
boolean n = false;
if (number < 0){ n = true; number *= -1; --l;}
breaker : for (byte LOL = 0; LOL < 1; LOL++){
if (StringHasChar(words, '.')){ words = "Decimals not supported."; break breaker;}
if (l>19){ words = "too big"; break breaker;}
if (l==1) words = oneDigit(number); // one digit
else if (l==2) words = twoDigits(number); // two digits
else if (l==3) words = threeDigits(number); // three digits
else words = nDigits(number); // multiple digits
}
if (n == true) {words = "Minus "+words; number *= -1;}
return words;
}
private static String oneDigit(long n){
char[] ns = Long.toString(n).toCharArray();
return od[(char2num(ns[0]))];
}
private static String twoDigits(long n){
String s = "";
char[] ns = Long.toString(n).toCharArray();
if (n < 20){
s = td[(char2num(ns[1]))];
} else if (n < 100){
s = tn[char2num(ns[0])];
if (char2num(ns[1])!=0){ s += " " + od[char2num(ns[1])]; }
}
return s;
}
private static String threeDigits(long n){
String s = "", is = Long.toString(n);
long[] ns = String2longArray(is);
s = od[(int)(ns[0])] + " hundred";
if (ns[1]!=0&&ns[2]!=0){
long i = (ns[1])*10+(ns[2]);
s += " " + twoDigits(i);
} else {
if (ns[1]!=0) s += " " + twoDigits((ns[1]*10));
if (ns[2]!=0) s += " " + oneDigit(ns[2]);
}
return s;
}
private static String nDigits(long n){
String s = threeDigits(n);
int tpi = ((digits(n)+2)/3)-1, rtpi = 0;
long[] tfr = threeFromRight(n);
s = "";
for (; tpi >= 0; tpi--, rtpi++){
s = new Num2Words(tfr[tpi]).toWords() + " " + tp[rtpi] + s;
}
return s;
}
private static int digits(long n){
long ans = 0;
for (; n>0; n/=10, ans++);
return (int)(ans);
}
private static long[] threeFromRight(long n){
int tpi = (digits(n)+2)/3, nl = digits(n);
long[] ans=new long[tpi], ia=String2longArray(Long.toString(n)), ta=new long[3];
for (int i=nl, t=2, c=0, l=tpi*3; l >= 0; l--, c++, i--, t--){
try {ta[t] = ia[i-1];}
catch (ArrayIndexOutOfBoundsException e){ta[t]=0;}
if (((c+1)%3)==0){
--tpi;
ans[tpi] = longArrays2long(ta);
t = 3;
c = -1;
}
}
return ans;
}
private static int char2num(char c){
char[] ca = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, ans = -1;
for (byte i = 0; i < 10; i++){ if (c == ca[i]){ ans = ia[i]; break;} }
return ans;
}
private static long[] String2longArray(String s){
char[] ca = s.toCharArray();
byte l = (byte)s.length();
long[] ans = new long[l];
for (byte i = 0; i < l; i++){ ans[i] = char2num(ca[i]); }
return ans;
}
private static long longArrays2long(long[] ia){
long ans = 0;
try { for (int i = 0; i >= 0; ans += ia[i], ans *= 10, ++i); }
catch (ArrayIndexOutOfBoundsException e){}
ans/=10;
return ans;
}
private static boolean StringHasChar(String s, char c){
char[] sca = s.toCharArray();
byte l = (byte)(s.length());
boolean ans = false;
for (byte i = 0; i > l; i++){
if (sca[i] == c) ans = true;
}
return ans;
}
public static void main(String[] args){
long n = -1053664648543756767l;
String words = new Num2Words(n).toWords();
System.out.println(n + " : " + words);
}
}
Note : The main(String[] args) is only for testing purposes. You may, or may not include it in your code.
Related
I have a string "aaabbb".
Below program returned max repeated value as a.
But here in this case both a and b are max repeated characters.
How can I print that both a and b as max repeated characters.
import java.util.HashMap;
import java.util.Map.Entry;
class MaxRepeatedCharactersInString
{
public static void main(String[] args)
{
String s = "acakabbba";
HashMap<Character, Integer> map = new HashMap<>();
char[] ch = s.toCharArray();
for(char c : ch)
{
if(map.containsKey(c))
{
map.put(c, map.get(c)+1);
}
else
{
map.put(c, 1);
}
}
int maxCount = 0;
char maxChar = ' ';
System.out.println("Maximum repeated character in String: ");
for(Entry<Character, Integer> entry : map.entrySet())
{
if(maxCount < entry.getValue())
{
maxCount = entry.getValue();
maxChar = entry.getKey();
}
}
System.out.println(maxChar+"="+maxCount);
}
}
I added an extra Stack and a counter to store the maximum repeated characters
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Stack;
class MaxRepeatedCharactersInString {
public static void main(String[] args) {
String s = "aa";
HashMap<Character, Integer> map = new HashMap<>();
char[] ch = s.toCharArray();
for (char c : ch) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int maxCount = 0;
int noMax = 0;
Stack<Character> st = new Stack<>();
System.out.println("Maximum repeated characters in String: ");
for (Entry<Character, Integer> entry : map.entrySet()) {
if (maxCount < entry.getValue()) {
maxCount = entry.getValue();
noMax = 1;
st.push(entry.getKey());
} else if (maxCount == entry.getValue()) {
noMax++;
st.push(entry.getKey());
}
}
for (int i = 0; i < noMax; i++) {
System.out.println(st.pop() + "=" + maxCount);
}
}
}
I need to write an application that fist converts a string to unicode and then add 2 to the unicode value to create a new string.
Basically, if the input is: password is RhYxtz, then the output should look like: rcuuyqtf ku TjAzvb
the following code is what I have so far:
public static void main(String[] args){
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
int currentChar2 = currentChar+2;
String s = String.format ("\\u%04x", currentChar2);
System.out.println ("Encoded message: " + s);
}
}
The problem is that I don't know how to convert the unicode back into a letter string and how to keep the format the same as the input. Could anyone help me? Thanks.
Unicode code points can be gathered in java 8 as:
public static String encryped(String s) {
int[] cps = s.codePoints()
.mapToInt((cp) -> cp + 2)
.toArray();
return new String(cps, 0, cps.length);
}
or in a loop with codePointAt in earlier versions.
Java char (2 bytes) are UTF-16, and their int value is not always a Unicode symbol aka code point.
Try this:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
System.out.print ("Enter text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
int length = text.length();
String s = "";
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar == ' '){
s += currentChar;
} else {
s += (char) (currentChar + 2);
}
}
System.out.println ("Encoded message: " + s);
}
}
This should work for US ASCII letters:
StringBuilder buf = new StringBuilder(length);
for(int i = 0; i < length; i ++){
char currentChar = text.charAt(i);
if (currentChar < 128 && Character.isLetter(currentChar)) {
if (currentChar == 'y' || currentChar == 'z'
|| currentChar == 'Y' || currentChar == 'Z') {
buf.append((char) (currentChar + 2 - 26));
} else {
buf.append((char) (currentChar + 2));
}
} else {
buf.append(currentChar);
}
}
System.out.println(buf.toString());
public string DecryptValue(string strText)
{
string DecriptedValue ="";
string String = strText.Substring(26); // This line fails
int Count = String.Length - 5;
string EncripEdText = String.Substring(0, Count);
int TotalChar = EncripEdText.Length / 2;
int J = 0;
for (int i = 1; i <= TotalChar; i++)
{
string EnChar = EncripEdText.Substring(J, 2);
string Decrypt = FindPos(EnChar);
DecriptedValue = DecriptedValue + Decrypt;
J = J + 2;
}
return DecriptedValue;
}
public static string FindPos(string EnChar)
{
string StringValue = "abcdefghijklmnopqrstuvwxyz0123456789_-.*#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string Value = StringValue.Substring(Convert.ToInt32(EnChar), 1);
return Value;
}
check for your argument length before taking the substring:
public string DecryptValue(string strText)
{
if (strText.Length<26)
{
MessageBox.Show("invalid argument length");
return;
}
string DecriptedValue ="";
string myString = strText.Substring(26); // This line fails
int myCount = myString.Length - 5;
...
}
How would the Jaro–Winkler distance string comparison algorithm be implemented in C#?
public static class JaroWinklerDistance
{
/* The Winkler modification will not be applied unless the
* percent match was at or above the mWeightThreshold percent
* without the modification.
* Winkler's paper used a default value of 0.7
*/
private static readonly double mWeightThreshold = 0.7;
/* Size of the prefix to be concidered by the Winkler modification.
* Winkler's paper used a default value of 4
*/
private static readonly int mNumChars = 4;
/// <summary>
/// Returns the Jaro-Winkler distance between the specified
/// strings. The distance is symmetric and will fall in the
/// range 0 (perfect match) to 1 (no match).
/// </summary>
/// <param name="aString1">First String</param>
/// <param name="aString2">Second String</param>
/// <returns></returns>
public static double distance(string aString1, string aString2) {
return 1.0 - proximity(aString1,aString2);
}
/// <summary>
/// Returns the Jaro-Winkler distance between the specified
/// strings. The distance is symmetric and will fall in the
/// range 0 (no match) to 1 (perfect match).
/// </summary>
/// <param name="aString1">First String</param>
/// <param name="aString2">Second String</param>
/// <returns></returns>
public static double proximity(string aString1, string aString2)
{
int lLen1 = aString1.Length;
int lLen2 = aString2.Length;
if (lLen1 == 0)
return lLen2 == 0 ? 1.0 : 0.0;
int lSearchRange = Math.Max(0,Math.Max(lLen1,lLen2)/2 - 1);
// default initialized to false
bool[] lMatched1 = new bool[lLen1];
bool[] lMatched2 = new bool[lLen2];
int lNumCommon = 0;
for (int i = 0; i < lLen1; ++i) {
int lStart = Math.Max(0,i-lSearchRange);
int lEnd = Math.Min(i+lSearchRange+1,lLen2);
for (int j = lStart; j < lEnd; ++j) {
if (lMatched2[j]) continue;
if (aString1[i] != aString2[j])
continue;
lMatched1[i] = true;
lMatched2[j] = true;
++lNumCommon;
break;
}
}
if (lNumCommon == 0) return 0.0;
int lNumHalfTransposed = 0;
int k = 0;
for (int i = 0; i < lLen1; ++i) {
if (!lMatched1[i]) continue;
while (!lMatched2[k]) ++k;
if (aString1[i] != aString2[k])
++lNumHalfTransposed;
++k;
}
// System.Diagnostics.Debug.WriteLine("numHalfTransposed=" + numHalfTransposed);
int lNumTransposed = lNumHalfTransposed/2;
// System.Diagnostics.Debug.WriteLine("numCommon=" + numCommon + " numTransposed=" + numTransposed);
double lNumCommonD = lNumCommon;
double lWeight = (lNumCommonD/lLen1
+ lNumCommonD/lLen2
+ (lNumCommon - lNumTransposed)/lNumCommonD)/3.0;
if (lWeight <= mWeightThreshold) return lWeight;
int lMax = Math.Min(mNumChars,Math.Min(aString1.Length,aString2.Length));
int lPos = 0;
while (lPos < lMax && aString1[lPos] == aString2[lPos])
++lPos;
if (lPos == 0) return lWeight;
return lWeight + 0.1 * lPos * (1.0 - lWeight);
}
}
You can take a look on Lucene.Net ,
it implement Jaro–Winkler distance algorithm ,
and its score is different from which leebickmtu post ,
you can take it as reference
the url is below :
http://lucenenet.apache.org/docs/3.0.3/db/d12/_jaro_winkler_distance_8cs_source.html
You can use the below code which works very well for all the kind of strings.After getting the result you need to multiply with 100 to get the percentage of similarity. I hope it will solves your problem.
public class JaroWinkler
{
private const double defaultMismatchScore = 0.0;
private const double defaultMatchScore = 1.0;
/// <summary>
/// Gets the similarity between two strings by using the Jaro-Winkler algorithm.
/// A value of 1 means perfect match. A value of zero represents an absolute no match
/// </summary>
/// <param name="_firstWord"></param>
/// <param name="_secondWord"></param>
/// <returns>a value between 0-1 of the similarity</returns>
///
public static double RateSimilarity(string _firstWord, string _secondWord)
{
// Converting to lower case is not part of the original Jaro-Winkler implementation
// But we don't really care about case sensitivity in DIAMOND and wouldn't decrease security names similarity rate just because
// of Case sensitivity
_firstWord = _firstWord.ToLower();
_secondWord = _secondWord.ToLower();
if ((_firstWord != null) && (_secondWord != null))
{
if (_firstWord == _secondWord)
//return (SqlDouble)defaultMatchScore;
return defaultMatchScore;
else
{
// Get half the length of the string rounded up - (this is the distance used for acceptable transpositions)
int halfLength = Math.Min(_firstWord.Length, _secondWord.Length) / 2 + 1;
// Get common characters
StringBuilder common1 = GetCommonCharacters(_firstWord, _secondWord, halfLength);
int commonMatches = common1.Length;
// Check for zero in common
if (commonMatches == 0)
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
StringBuilder common2 = GetCommonCharacters(_secondWord, _firstWord, halfLength);
// Check for same length common strings returning 0 if is not the same
if (commonMatches != common2.Length)
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
// Get the number of transpositions
int transpositions = 0;
for (int i = 0; i < commonMatches; i++)
{
if (common1[i] != common2[i])
transpositions++;
}
int j = 0;
j += 1;
// Calculate Jaro metric
transpositions /= 2;
double jaroMetric = commonMatches / (3.0 * _firstWord.Length) + commonMatches / (3.0 * _secondWord.Length) + (commonMatches - transpositions) / (3.0 * commonMatches);
//return (SqlDouble)jaroMetric;
return jaroMetric;
}
}
//return (SqlDouble)defaultMismatchScore;
return defaultMismatchScore;
}
/// <summary>
/// Returns a string buffer of characters from string1 within string2 if they are of a given
/// distance seperation from the position in string1.
/// </summary>
/// <param name="firstWord">string one</param>
/// <param name="secondWord">string two</param>
/// <param name="separationDistance">separation distance</param>
/// <returns>A string buffer of characters from string1 within string2 if they are of a given
/// distance seperation from the position in string1</returns>
private static StringBuilder GetCommonCharacters(string firstWord, string secondWord, int separationDistance)
{
if ((firstWord != null) && (secondWord != null))
{
StringBuilder returnCommons = new StringBuilder(20);
StringBuilder copy = new StringBuilder(secondWord);
int firstWordLength = firstWord.Length;
int secondWordLength = secondWord.Length;
for (int i = 0; i < firstWordLength; i++)
{
char character = firstWord[i];
bool found = false;
for (int j = Math.Max(0, i - separationDistance); !found && j < Math.Min(i + separationDistance, secondWordLength); j++)
{
if (copy[j] == character)
{
found = true;
returnCommons.Append(character);
copy[j] = '#';
}
}
}
return returnCommons;
}
return null;
}
}
Use below class to use jaro winkler.
i have customized both algorithm jaro and jaro-winkler.
Visit on Github for DLL.
using System;
using System.Linq;
namespace Search
{
public static class EditDistance
{
private struct JaroMetrics
{
public int Matches;
public int Transpositions;
}
private static EditDistance.JaroMetrics Matches(string s1, string s2)
{
string text;
string text2;
if (s1.Length > s2.Length)
{
text = s1;
text2 = s2;
}
else
{
text = s2;
text2 = s1;
}
int num = Math.Max(text.Length / 2 - 1, 0);
int[] array = new int[text2.Length];
int i;
for (i = 0; i < array.Length; i++)
{
array[i] = -1;
}
bool[] array2 = new bool[text.Length];
int num2 = 0;
for (int j = 0; j < text2.Length; j++)
{
char c = text2[j];
int k = Math.Max(j - num, 0);
int num3 = Math.Min(j + num + 1, text.Length);
while (k < num3)
{
if (!array2[k] && c == text[k])
{
array[j] = k;
array2[k] = true;
num2++;
break;
}
k++;
}
}
char[] array3 = new char[num2];
char[] ms2 = new char[num2];
i = 0;
int num4 = 0;
while (i < text2.Length)
{
if (array[i] != -1)
{
array3[num4] = text2[i];
num4++;
}
i++;
}
i = 0;
num4 = 0;
while (i < text.Length)
{
if (array2[i])
{
ms2[num4] = text[i];
num4++;
}
i++;
}
int num5 = array3.Where((char t, int mi) => t != ms2[mi]).Count<char>();
EditDistance.JaroMetrics result;
result.Matches = num2;
result.Transpositions = num5 / 2;
return result;
}
public static float JaroWinkler(this string s1, string s2, float prefixScale, float boostThreshold)
{
prefixScale = ((prefixScale > 0.25f) ? 0.25f : prefixScale);
prefixScale = ((prefixScale < 0f) ? 0f : prefixScale);
float num = s1.Jaro(s2);
int num2 = 0;
for (int i = 0; i < Math.Min(s1.Length, s2.Length); i++)
{
if (s1[i] != s2[i])
{
break;
}
num2++;
}
return (num < boostThreshold) ? num : (num + prefixScale * (float)num2 * (1f - num));
}
public static float JaroWinkler(this string s1, string s2, float prefixScale)
{
return s1.JaroWinkler(s2, prefixScale, 0.7f);
}
public static float JaroWinkler(this string s1, string s2)
{
return s1.JaroWinkler(s2, 0.1f, 0.7f);
}
public static float Jaro(this string s1, string s2)
{
EditDistance.JaroMetrics jaroMetrics = EditDistance.Matches(s1, s2);
float num = (float)jaroMetrics.Matches;
int transpositions = jaroMetrics.Transpositions;
float result;
if (num == 0f)
{
result = 0f;
}
else
{
float num2 = (num / (float)s1.Length + num / (float)s2.Length + (num - (float)transpositions) / num) / 3f;
result = num2;
}
return result;
}
public static int LevenshteinDistance(this string source, string target)
{
int result;
if (string.IsNullOrEmpty(source))
{
if (string.IsNullOrEmpty(target))
{
result = 0;
}
else
{
result = target.Length;
}
}
else if (string.IsNullOrEmpty(target))
{
result = source.Length;
}
else
{
if (source.Length > target.Length)
{
string text = target;
target = source;
source = text;
}
int length = target.Length;
int length2 = source.Length;
int[,] array = new int[2, length + 1];
for (int i = 1; i <= length; i++)
{
array[0, i] = i;
}
int num = 0;
for (int j = 1; j <= length2; j++)
{
num = (j & 1);
array[num, 0] = j;
int num2 = num ^ 1;
for (int i = 1; i <= length; i++)
{
int num3 = (target[i - 1] == source[j - 1]) ? 0 : 1;
array[num, i] = Math.Min(Math.Min(array[num2, i] + 1, array[num, i - 1] + 1), array[num2, i - 1] + num3);
}
}
result = array[num, length];
}
return result;
}
}
}
What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.
Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...
String str = "Hello, there, everyone?";
StringBuffer result = new StringBuffer(str.length());
String strl = str.toLowerCase();
boolean bMustCapitalize = false;
for (int i = 0; i < strl.length(); i++)
{
char c = strl.charAt(i);
if (c >= 'a' && c <= 'z')
{
if (bMustCapitalize)
{
result.append(strl.substring(i, i+1).toUpperCase());
bMustCapitalize = false;
}
else
{
result.append(c);
}
}
else
{
bMustCapitalize = true;
}
}
System.out.println(result);
You can replace the convoluted uppercase append with:
result.append((char) (c - 0x20));
although it might seem more hackish.
With CDC, you have:
String.getBytes();//to convert the string to an array of bytes
String.indexOf(int ch); //for locating the beginning of the words
String.trim();//to remove spaces
For lower/uppercase you need to add(subtract) 32.
With these elements, you can build your own method.
private static String toCamelCase(String s) {
String result = "";
String[] tokens = s.split("_"); // or whatever the divider is
for (int i = 0, L = tokens.length; i<L; i++) {
String token = tokens[i];
if (i==0) result = token.toLowerCase();
else
result += token.substring(0, 1).toUpperCase() +
token.substring(1, token.length()).toLowerCase();
}
return result;
}
Suggestion:
May be if you can port one regexp library on J2ME, you could use it to strip spaces in your String...
Try following code
public static String toCamel(String str) {
String rtn = str;
rtn = rtn.toLowerCase();
Matcher m = Pattern.compile("_([a-z]{1})").matcher(rtn);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
rtn = sb.toString();
return rtn;
}
I would suggest the following simple code:
String camelCased = "";
String[] tokens = inputString.split("\\s");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
camelCased = camelCased + token.substring(0, 1).toUpperCase() + token.substring(1, token.length());
}
return camelCased;
I would do it like this:
private String toCamelCase(String s) {
StringBuffer sb = new StringBuffer();
String[] x = s.replaceAll("[^A-Za-z]", " ").replaceAll("\\s+", " ")
.trim().split(" ");
for (int i = 0; i < x.length; i++) {
if (i == 0) {
x[i] = x[i].toLowerCase();
} else {
String r = x[i].substring(1);
x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r;
}
sb.append(x[i]);
}
return sb.toString();
}
check this
import org.apache.commons.lang.WordUtils;
String camel = WordUtils.capitalizeFully('I WANT TO BE A CAMEL', new char[]{' '});
return camel.replaceAll(" ", "");