String/Array in Java - string

Does this work? I'm trying to print a message in this.
char[] tempMessage = message.toCharArray();
String[] message2 = message.split(" ");
Integer.toString(number).toCharArray();
for(int x = 0; x<newMessage.length; x++)
{
}

Although its better to use a StringBuilder, I can show it using String(s).
String[] strArr = "hello world".split("\\s+");
String s = String.valueOf(strArr[0].charAt(0))+strArr[0].length()+String.valueOf(strArr[1].charAt(0))+strArr[1].length();
Output : h5w5

String[] message2 = message.split("\\s+");
String output = "";
for(int i = 0; i < message2.length; i++)
{
output += "" + message2[i].charAt(0) + message2[i].length();
}
//output has output string.

TheLostMind's solution is already good, but I think it needs a solution for Strings of arbitrary length.
String outputString = "";
for(String x : message.split("\\s+"))
{
outputString = outputString.concat(x.charAt(0) + x.length());
}
As stated in the comments, this solution is very similiar to brso05's solution. The difference is in using the :-Operator in the for-loop. It's shorter and IMHO easier to understand, as it says 'for each String in the resulting array'.
Also, using the concat()-function is considered safer in my work environment.

Related

Remove duplicate string elements C++

The problem consists of finding all permutations using k out of n digits. I'm able to find all the permutations, but I'm struggling trying to erase duplicates. I can successfully compare and find the duplicates, but erasing them is what I'm struggling to do. I have a feeling I'm missing something simple but I don't know what it is.
Any help would be greatly appreciated. I've been staring at this for a week.
Here is the code that I've got right now.
void getPermutations(int n, int k)
{
string str = "";
//fill string with numbers <= n
for(int i = 0; i < n; i++)
{
str += to_string(i); //convert numbers to string
}
string tempStr = "";
string outputStr = "";
do {
tempStr = str.substr(0, k);
int compareResult = tempStr.compare(0, k, outputStr, 0, k);
if (compareResult == 0)
{
cout << "| same | ";
outputStr.erase(k,k);
}
outputStr = tempStr;
cout << outputStr << " ";
} while (next_permutation(str.begin(), str.end()));
}
I think what you meant to do was to erase the contents of tempStr, not outputStr.
The call to erase is not exactly right. Its first argument marks the starting position of your erasing, and the second argument tells how many characters to erase. So if you want to erase the whole string, the first argument should be...
You actually don't have to erase anything. After you get it working your way, try to do it without erasing!
Good Luck!

How to find SHA1 hash?

i got interesting task at school. I have to find message which sha-1 hash lasts with my birthday example. if i was born on 4th may 1932 then the hash must end with 040532. Any suggestions how to find it out?
my solution in C#:
//A create Sha1 function:
using System.Security.Cryptography;
public static string GetSHA1Hash(string text)
{
var SHA1 = new SHA1CryptoServiceProvider();
byte[] arrayData;
byte[] arrayResult;
string result = null;
string temp = null;
arrayData = Encoding.ASCII.GetBytes(text);
arrayResult = SHA1.ComputeHash(arrayData);
for (int i = 0; i < arrayResult.Length; i++)
{
temp = Convert.ToString(arrayResult[i], 16);
if (temp.Length == 1)
temp = "0" + temp;
result += temp;
}
return result;
}
Source
Then a Random String generator:
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
Source
and now you can bruteforce for your combination:
string search = "32";
string result = String.Empty;
int slen = 5;
string myTry = RandomString(slen);
while (!result.EndsWith(search))
{
myTry = RandomString(slen);
result = GetSHA1Hash(myTry);
}
MessageBox.Show(result + " " + myTry);
This would search for a Hash String ending with 32. Happy Bruteforcing :)
EDIT: found one for your example: HXMQVNMRFT gives e5c9fa9f6acff07b89c617c7fd16a9a043040532
Start generating hashes from distinct messages1.
Eventually a hash will be generated with such a property. This is not that bad to brute-force as the range is only 224 (or ~16 million) and SHA is very fast.
There is no shortcut as SHA is a one way cryptographic hash function. In particular here, SHA has the property that "it is infeasible to generate a message that has a given hash".
1 The inputs should be distinct, and a simple counter will suffice. However, it may be more interesting to generate quasi-random messages based on the birthday being sought - e.g. including the date in various forms and sentences Mad Lib style. As long as this doesn't limit the domain, such that there is no qualifying hash, it'll work just as well as any other set of source messages.

How can I parse a String[] to an int[] in java?

I have the code:
String s = "a,b,c,d,e";
int[] i = s.split(",");
but this cast is not avaiable.
Some one can help me?
Thanks
You must loop over each element in the array and cast them one by one.
Like this:
String s = "a,b,c,d,e";
String[] strings = s.split(",");
int[] i = new int[strings.length];
for(int j = 0; j < strings.length; j++)
{
i[j] = Integer.parseInt(strings[j]);
}
Note that this code will crash, since the elements in the string-array aren't integers.
Java is strongly-typed which means it won't allow you to cast between incompatible types. In order to convert between integers and strings, you need to explicitly do the conversion. Integer.parseInt can convert a string to an integer. So you will need to loop through your array and convert each integer to a string individually.
String[] strings = "a,b,c,d,e".split(",");
int parsedIntegers[] = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
parsedIntegers[i] = Integer.parseInt(strings[i]);
}

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);
Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.
Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.
Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

Format string to title case

How do I format a string to title case?
Here is a simple static method to do this in C#:
public static string ToTitleCaseInvariant(string targetString)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}
I would be wary of automatically upcasing all whitespace-preceded-words in scenarios where I would run the risk of attracting the fury of nitpickers.
I would at least consider implementing a dictionary for exception cases like articles and conjunctions. Behold:
"Beauty and the Beast"
And when it comes to proper nouns, the thing gets much uglier.
Here's a Perl solution http://daringfireball.net/2008/05/title_case
Here's a Ruby solution http://frankschmitt.org/projects/title-case
Here's a Ruby one-liner solution: http://snippets.dzone.com/posts/show/4702
'some string here'.gsub(/\b\w/){$&.upcase}
What the one-liner is doing is using a regular expression substitution of the first character of each word with the uppercase version of it.
To capatilise it in, say, C - use the ascii codes (http://www.asciitable.com/) to find the integer value of the char and subtract 32 from it.
This is a poor solution if you ever plan to accept characters beyond a-z and A-Z.
For instance: ASCII 134: å, ASCII 143: Å.
Using arithmetic gets you: ASCII 102: f
Use library calls, don't assume you can use integer arithmetic on your characters to get back something useful. Unicode is tricky.
In Silverlight there is no ToTitleCase in the TextInfo class.
Here's a simple regex based way.
Note: Silverlight doesn't have precompiled regexes, but for me this performance loss is not an issue.
public string TitleCase(string str)
{
return Regex.Replace(str, #"\w+", (m) =>
{
string tmp = m.Value;
return char.ToUpper(tmp[0]) + tmp.Substring(1, tmp.Length - 1).ToLower();
});
}
In Perl:
$string =~ s/(\w+)/\u\L$1/g;
That's even in the FAQ.
If the language you are using has a supported method/function then just use that (as in the C# ToTitleCase method)
If it does not, then you will want to do something like the following:
Read in the string
Take the first word
Capitalize the first letter of that word 1
Go forward and find the next word
Go to 3 if not at the end of the string, otherwise exit
1 To capitalize it in, say, C - use the ascii codes to find the integer value of the char and subtract 32 from it.
There would need to be much more error checking in the code (ensuring valid letters etc.), and the "Capitalize" function will need to impose some sort of "title-case scheme" on the letters to check for words that do not need to be capatilised ('and', 'but' etc. Here is a good scheme)
In what language?
In PHP it is:
ucwords()
example:
$HelloWorld = ucwords('hello world');
In Java, you can use the following code.
public String titleCase(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i == 0) {
chars[i] = Character.toUpperCase(chars[i]);
} else if ((i + 1) < chars.length && chars[i] == ' ') {
chars[i + 1] = Character.toUpperCase(chars[i + 1]);
}
}
return new String(chars);
}
Excel-like PROPER:
public static string ExcelProper(string s) {
bool upper_needed = true;
string result = "";
foreach (char c in s) {
bool is_letter = Char.IsLetter(c);
if (is_letter)
if (upper_needed)
result += Char.ToUpper(c);
else
result += Char.ToLower(c);
else
result += c;
upper_needed = !is_letter;
}
return result;
}
http://titlecase.com/ has an API
There is a built-in formula PROPER(n) in Excel.
Was quite pleased to see I didn't have to write it myself!
Here's an implementation in Python: https://launchpad.net/titlecase.py
And a port of this implementation that I've just done in C++: http://codepad.org/RrfcsZzO
Here is a simple example of how to do it :
public static string ToTitleCaseInvariant(string str)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);
}
I think using the CultureInfo is not always reliable, this the simple and handy way to manipulate string manually:
string sourceName = txtTextBox.Text.ToLower();
string destinationName = sourceName[0].ToUpper();
for (int i = 0; i < (sourceName.Length - 1); i++) {
if (sourceName[i + 1] == "") {
destinationName += sourceName[i + 1];
}
else {
destinationName += sourceName[i + 1];
}
}
txtTextBox.Text = desinationName;
In C#
using System.Globalization;
using System.Threading;
protected void Page_Load(object sender, EventArgs e)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
Response.Write(textInfo.ToTitleCase("WelcometoHome<br />"));
Response.Write(textInfo.ToTitleCase("Welcome to Home"));
Response.Write(textInfo.ToTitleCase("Welcome#to$home<br/>").Replace("#","").Replace("$", ""));
}
In C# you can simply use
CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLowerInvariant())
Invariant
Works with uppercase strings
Without using a ready-made function, a super-simple low-level algorithm to convert a string to title case:
convert first character to uppercase.
for each character in string,
if the previous character is whitespace,
convert character to uppercase.
This asssumes the "convert character to uppercase" will do that correctly regardless of whether or not the character is case-sensitive (e.g., '+').
Here you have a C++ version. It's got a set of non uppercaseable words like prononuns and prepositions. However, I would not recommend automating this process if you are to deal with important texts.
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <set>
using namespace std;
typedef vector<pair<string, int> > subDivision;
set<string> nonUpperCaseAble;
subDivision split(string & cadena, string delim = " "){
subDivision retorno;
int pos, inic = 0;
while((pos = cadena.find_first_of(delim, inic)) != cadena.npos){
if(pos-inic > 0){
retorno.push_back(make_pair(cadena.substr(inic, pos-inic), inic));
}
inic = pos+1;
}
if(inic != cadena.length()){
retorno.push_back(make_pair(cadena.substr(inic, cadena.length() - inic), inic));
}
return retorno;
}
string firstUpper (string & pal){
pal[0] = toupper(pal[0]);
return pal;
}
int main()
{
nonUpperCaseAble.insert("the");
nonUpperCaseAble.insert("of");
nonUpperCaseAble.insert("in");
// ...
string linea, resultado;
cout << "Type the line you want to convert: " << endl;
getline(cin, linea);
subDivision trozos = split(linea);
for(int i = 0; i < trozos.size(); i++){
if(trozos[i].second == 0)
{
resultado += firstUpper(trozos[i].first);
}
else if (linea[trozos[i].second-1] == ' ')
{
if(nonUpperCaseAble.find(trozos[i].first) == nonUpperCaseAble.end())
{
resultado += " " + firstUpper(trozos[i].first);
}else{
resultado += " " + trozos[i].first;
}
}
else
{
resultado += trozos[i].first;
}
}
cout << resultado << endl;
getchar();
return 0;
}
With perl you could do this:
my $tc_string = join ' ', map { ucfirst($\_) } split /\s+/, $string;

Resources