I'm trying to combine two sentences word by word in java without using any special string methods except charAt and length.
It's like
String s1="hello world";
String s2="programmers are greeting"
I want to combine that two string get one word from s1 then get one word from s2 and keep until there is no word left in s1 and s2 in s3.
String s3="hello programmers world are greeting"
Here's my method but when I run it doesn't return anything. I couldn't find the problem:
void combine(String str1, String str2) {
int i,
j,
sl1,
sl2,
s,
test;
sl1 = str1.length();
sl2 = str2.length();
test = sl1 + sl2;
char[] ar1 = new char[sl1];
char[] ar2 = new char[sl2];
for (i = 0; i < ar1.length; i++)
{
ar1[i] = str1.charAt(i);
}
for (j = 0; j < ar2.length; j++)
{
ar2[j] = str2.charAt(j);
}
char[] array = new char[test];
s = array.length;
i = 0;
j = 0;
while (s <= i + j) {
while (ar1[i] != ' ')
{
if (i == sl1) break;
array[i + j] = ar1[i];
i = i + 1;
}
while (ar2[j] != ' ')
{
if (j == sl2) break;
array[j + i] = ar2[j];
j = j + 1;
}
}
for (i = 0; i < s; i++)
{
System.out.print(array[i]);
}
}
The method combine is void which should become int otherwise you should output the answer using a System.out.println();
Related
The following code is supposed to convert letters to numbers and give the sum, but ignore any letters that are uppercase.
Example:
The input abcde should return 15. The input abCde should return 12.
Any help is appreciated.
static int strScore(String str[], String s, int n) {
int score = 0, index=0;
for (int i = 0; i < n; i++) {
if (str[i] == s) {
for (int j = 0; j < s.length(); j++)
score += s.charAt(j) - 'a' + 1;
index = i + 1;
break;
}
}
score = score * index;
return score;
}
public static void main(String[] args) {
String str[] = { "abcde" };
String s = "abcde";
int n = str.length;
int score = strScore(str, s, n);
System.out.println( score);
}
Use Character.isLowerCase(...).
So this is what your strScore method should look like:
static int strScore(String str[], String s, int n) {
int score = 0, index = 0;
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if(Character.isLowerCase(c)) // <-- This is the important part
score += c - 'a' + 1;
}
index = i + 1;
break;
}
}
score = score * index;
return score;
}
As pointed out in the comments, there is no need for the str and therfore neither the n parameter. This is a better version:
static int strScore(String s) {
int score = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
return score;
}
There are two things to address:
You have used == to compare strings. You need to use .equals
You need to put a check like if(s.charAt(j)>= 'a' && s.charAt(j)<'z')
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++)
if(s.charAt(j)>= 'a' && s.charAt(j)<'z') {
score += s.charAt(j) - 'a' + 1;
You can avoid passing String str[] = { "abcde" }; which has one element which equals s
to The method. You can also avoid passing n which is an simply str.length():
static int strScore(String s) {
int score = 0, index = 0;
for (int i = 0; i < s.length(); i++) {
for (char c : s.toCharArray()) {
if(c >= 'a' && c <'z') { //alternatively if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
}
index = i + 1;
break;
}
score = score * index;
return score;
}
public class test
{
static Scanner store = new Scanner(System.in);
public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
System.out.printf("%nThere are %d dissimilar characters in the two strings.%n", CountNotSim(str1, str2));
}
public static int CountNotSim(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
char[] a1 = new char[s1.length()];
char[] a2 = new char[s2.length()];
for (int g = 0; g < s1.length(); g++)
a1[g] = s1.charAt(g);
for (int h = 0; h < s2.length(); h++)
a2[h] = s2.charAt(h);
int check = 0, stored;
char[] array = new char[26];
int ctr = s1.length() + s2.length();
for (int i = 0; i < a1.length; i++)
{
check = 0;
stored = 0;
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j])
{
check++;
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ')
if (stored == 0)
array[k] = a1[i];
if (a1[i] == array[k])
{
stored = 1;
break;
}
}
System.out.print(stored + "/ ");
}
}
if (check > 0)
{
if (stored == 0)
ctr -= (check + 1);
else if (stored == 1)
ctr--;
}
System.out.print(ctr + " "); //checker
}
System.out.println();
return ctr;
}
}
The program checks for dissimilar letters in two strings inputted from the command line. Variable "stored" is supposed to change to 1 whenever there's a match to avoid extra deductions to variable "ctr". However, for some reason, not only does "stored's" value not change, the array "array" also doesn't update its elements whenever there's a match. I'm at a loss on how to fix it--nothing looks incorrect.
You wrote this:
char[] array = new char[26];
...
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ') {
...
But you simply set the length of array not its content.
As a char array, it's filled with the default char value, which is not the character space but the value 0 (not the character 0, but the numeric value 0)
So array[k] == ' ' will never be true.
Try with that:
for (int k = 0; k < 26; k++)
{
if (array[k] == 0) {
...
I am trying to return a string so that it is not printed in the function but rather in the main class.
I have tried to concatenate the string on every character that comes out so that the string keeps growing depending on the inputted number.
public class Main {
public static void main(String[] args) {
Diamond print = new Diamond();
output = print.print(5);
System.out.print(output);
}
}
class Diamond {
public static String print(int n) {
String concat = "";
if(!(n % 2 == 0)) {
for (int i = 1; i < n; i += 2) {
for (int k = n; k >= i; k -= 2) {
System.out.print(" ");
concat = concat.(" ");//what i am trying to do :(
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
concat = concat.("*");
}
concat = concat.("\n");
System.out.println();
}// end loop
for (int i = 1; i <= n; i += 2) {
for (int k = 1; k <= i; k += 2) {
System.out.print(" ");
}
for (int j = n; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}// end loop
}
return concat;
}
}
use the concat() method
String str = "";
str = str.concat("blabla");
but since your variable name is concat then do like this:
String concat = "";
concat = concat.concat("blabla");
however, using StringBuffer is better..
StringBuffer sb = new StringBuffer();
sb.append("blabla");
then.. for the output, return the string by writing: sb.toString();
I am using this code for sentence similarties the code is available on java i want to use this in c#.
public static int getWordChanges(String s1, String s2) {
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
s2 = s2.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.split(" ").length; i++) {
boolean exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.split(" ").length; j++) {
//Is the word misspelled?
if ((getLevenshteinDistance(s1.split(" ")[i], s2.split(" ")[j]) * 100 / s1.split(" ")[i].length()) < similarityThreshold) {
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists) {
wordChanges++;
}
}
return wordChanges;
}
This is Java code i want to execute this code in c#
After convert the code in c#
public int getWordChanges(String s1, String s2)
{
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
s2 = s2.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.Split(' ').Length; i++)
{
bool exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.Split(' ').Length; j++)
{
//Is the word misspelled?
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
{
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists)
{
wordChanges++;
}
}
return wordChanges;
}
}
}
There are error at this line
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
on length error will show how i resolve this one
Add this function to your project
public static int getLevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
Source
And change .Length() to .Length Because String.Length is a property and not a method
I have a method that supposed to delete all the dups from string passed inside it. I can print the dups, how can I delete them in the original string ? Say, 'miami' will need to be 'mia' when it will return. Thanks.
public static String removeDups( String str1){
char[] str = str1.toCharArray();
if (str == null) return null;
int len = str.length;
if (len < 2) return new String(str);
char[] newStr = new char[len+1];
int copyLength = 0;
for ( int i = 1 ; i < len; i++){
for( int j=0; j< i; j++){
if ( str[i] == str[j]){
System.out.println(" str[i] == str[j] = "+ str[i] + " , "+str[j]);
break;
}
}
}
return new String(str);
}
I found this to be easier using a StringBuilder rather than a String
EDIT
This can also be done with a combination of StringBuilder and regex
Regex Pattern breakdown:
(.) --> matches any character and puts in group 1.
?= --> this is called a positive lookahead.
?=.*\\1 --> positive lookahead of zero or more characters for the first group
Code Sample:
public static void main(String[] args) throws Exception {
System.out.println(removeDuplicates("miamimiamimiami"));
System.out.println(removeDuplicatesRegex("miamimiamimiami"));
}
public static String removeDuplicates(String input){
StringBuilder data = new StringBuilder(input);
for (int i = 0; i < data.length(); i++) {
String character = String.valueOf(data.charAt(i));
int dupIndex = data.indexOf(character, i + 1);
while (dupIndex != -1) {
data.deleteCharAt(dupIndex);
dupIndex = data.indexOf(character, i + 1);
}
}
return data.toString();
}
public static String removeDuplicatesRegex(String input) {
return new StringBuilder(
new StringBuilder(input)
.reverse()
.toString()
.replaceAll("(.)(?=.*\\1)", ""))
.reverse().toString();
}
Results:
mia
mia
Here's another option:
StringBuffer buf = new StringBuffer( originalString);
int len = str.length();
for (int i = 0; i < len; i++) {
char c = buf.charAt( i );
for (int j = len - 1; j > i; j--) {
if ( buf.charAt( j ) == c ) {
buf.deleteCharAt( j );
len--;
}
}
}
Remove all duplicate chars in a String:
public static String removeDuplicates(String str1) {
if (str1 == null)
return null;
char[] str = str1.toCharArray();
int len = str.length;
if (len < 2)
return str1;
char temp = str[0];
for (int i = 1; i < len; i++) {
if (temp != 0)
for (int j = i; j < len; j++)
if (temp == str[j])
str[j] = 0;
temp = str[i];
}
int i = 0;
char[] str2 = new char[len];
for (char c : str)
if (c != 0)
str2[i++] = c;
return (new String(str2)).trim();
}
You can also use Arraylist to store the unique characters:
public static String removeDups( String str1){
ArrayList<Character> set=new ArrayList<Character>();
char[] str=str1.toCharArray();
for(int i=0;i<str.length;i++)
{
if(!set.contains(str[i])){
set.add(str[i]);
}
}
for(char e:set)
{
System.out.print(e);
}
}
Your loop seems to be a bit strange.
char[] str = str1.toCharArray();
int len = str.length;
if (str == null || len < 2) return null;
char[] newStr = new char[len+1];
int newStrLength = 0;
for( int i = 1; i < len; i++ ){ //Iterate complete string
for( int j=0; j < i; j++ ){ //Iterate the already-finished part
if( str[i] == str[j] )
break;
}
newStr[newStrLength++] = str[i];
}
}
newStr[newStrLength] = 0;
In this example I make a completly new string and don't alter the original one. It makes the code clearer to read.
Alternatively you could take a look at this question which has some more efficient answers.