For all of the following words, if you move the first letter to the end of the
word, and then spell the result backwards, you will get the original word:
banana dresser grammar potato revive uneven assess
I got the first part down, moving the first letter to the end, but I am not able to spell the word in reverse. I have to use a for loop for this, but I have no idea how to use it so it will spell the rest of the word backwards.
Normally the for-loop does not care in which way you modify the index, so you should be able to use something like
string firstAtLast = "otatop";
string reverse = "";
for(int i=string.length-1; i => 0; i--)
{
reverse += firstAtLast.At(i)
}
Details for i and the string manipulation methods depend on your language of course.
This should do the trick (C#)
public void ReverseWord()
{
var word = "banana dresser grammar potato revive uneven assess";
var length = word.Length;
string reverse = "";
for (int i = 0; i < length; i++)
{
reverse = word.Substring(0, 1) + reverse;
word = word.Remove(0, 1);
}
}
The result I'm getting is : ssessa nevenu eviver otatop rammarg resserd ananab
Why would you move the first letter to the end?
string word = "hello";
string neword = string.Empty;
Array a = word.ToCharArray();
foreach (char c in a)
{
neword = neword + c;
}
I wrote that in C#, but its the same for mainly anything.
Actually, you might be able to do it this way if the language you are writing in is a bit smart:
string word = "hello";
string neword = string.Empty;
foreach (char c in word)
{
neword = neword + c;
}
Related
I'm trying to make a code that removes all the elements from the array that are equal to a given value. For example an array = [hi, hello, hi, bye] value = hi, it would given an output hello bye
Here's my code:
int count = 0;
for(int i=0; i<stringArr.length;
if(stringArr[i].equals(value)){
count--;
for(int j= i; j<stringArr.length-1; j++){
stringArr[j] = stringArr[j+1];
}
i--;
}
}
Problem is instead of the expected output as: hello bye
It gives an output of:
hello hi bye bye
Try Java stream api:
String value = "hi";
String[] stringArr = new String[] {"hi", "hello", "hi", "bye"};
String[] results = Arrays.stream(stringArr)
.filter(it -> !it.equalsIgnoreCase(value))
.toArray(String[]::new);
The problem is that you are shifting the values left but not decrementing the length of the array in the outer for.
Assign stringArr.length to count and use it in the for.
Trading memory for speed, you could create a new array of the same length and only add in the first occurrence of what you want.
String[] removeEqual(String[]array,String val){
boolean found =false;
String[]out=new String[array.length];
int count=0;
for (int i=0;i<array.length;i++){
if(array[i].equals(val)){
if(!found){
out[count++]=val;
found=true;
}
else out[count++]=val;
}
}
return Arrays.copyOf(out, count);
}
You may like to consider separate functions for separate conditions such as removeLessThan and removeGreaterThan to keep it functionally coherent.
I don't recommend to do any manipulation to the original array, create a new one. Recycling is good for the planet, but may be very harmful in code. So if you want to stick to the Arrays only, then create a new array with and add all elements you want into the new array, but I think you can do better. Your approach is very "C" like, this is Java, you have a lot of better tools, than arrays.
One of them are streams and lambdas like this
#Test
public void example_lambdas() {
String[] array = {"hi", "hello", "hi", "bye"};
String[] result = Arrays.stream(array).filter(element -> !"hi".equals(element)).toArray(String[]::new);
System.out.println(Arrays.toString(result));
}
Another option is to use list
#Test
public void example_list() {
String[] array = {"hi", "hello", "hi", "bye"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Set<String> toBeRemoved = Collections.singleton("hi");
list.removeAll(toBeRemoved);
String[] result = list.toArray(new String[0]);
System.out.println(Arrays.toString(result));
}
An array has a fixed size that cannot be changed. Hence your result cannot be a two element array when you start with a four element array. If you want the result to be a two element array, then you will need to create a second array. If, however, you want the result to stay in the original array, then I suggest setting the excess array elements to null. The following code demonstrates.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
int count = stringArr.length;
for (int i = 0; i < count; i++) {
if (condition.equals("==")) {
if (stringArr[i].equals(value)) {
count--;
for (int j = i; j < stringArr.length - 1; j++) {
stringArr[j] = stringArr[j + 1];
}
stringArr[stringArr.length - 1] = null;
}
}
}
System.out.println(java.util.Arrays.toString(stringArr));
The above code prints the following:
[hello, bye, null, null]
EDIT
As requested, below code creates a new array that only contains the requested elements, i.e. the ones that were not removed from the original array.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
String[] temp = new String[stringArr.length];
int count = 0;
for (int i = 0; i < stringArr.length; i++) {
if (condition.equals("==")) {
if (!stringArr[i].equals(value)) {
temp[count++] = stringArr[i];
}
}
}
String[] result = new String[count];
for (int i = 0; i < count; i++) {
result[i] = temp[i];
}
System.out.println(Arrays.toString(result));
The above code prints the following:
[hello, bye]
In other words, result is a two element array.
Note that I assume that you only want to do array manipulation and you don't want to use classes in the JDK that most of the other answers have used.
I'm trying to print a reversed string/array. I've used the following code and it seems to be able to give my second array, revString, values in the correct order from the first array string. I am also able to print individual characters in both arrays, and I'm able to print the entire string of the first array. However the revString array doesn't print at all. I'm wondering if I am missing a huge point here.
void reverseString(char string[]) {
int i = strlen(string);
int i_2 = 0;
revString arrayet
char revString[i + 1];
char *character;
while (i > -1) {
character = &string[i];
revString[i_2] = *character;
printf("%c", revString[i_2]);
i = i - 1;
i_2 = i_2 + 1;
}
revString[i_2] = '\0';
printf("%d\n", i_2);
printf("%s", revString);
}
The code gives now the following output with example string "Hello World";
dlrow olleH13
As you can see the final printf statement doesn't do anything
In C language indexing is 0 based. so, if you make a string of 10 length, the last character will be at index 9.
In your code, when you are assigning characters to revString, your code is trying to access string[len].
your code should be like this..
int i = strlen(string) - 1;
Your code reverses the string string including the null terminator at string[i]. The resulting array starts with a null terminator, hence printf outputs nothing.
Here is a modified version:
void reverseString(char string[]) {
int i = strlen(string);
int i_2 = 0;
char revString[i + 1];
char character;
while (i > 0) {
i = i - 1;
character = string[i];
revString[i_2] = character;
//printf("%c", revString[i_2]);
i_2 = i_2 + 1;
}
revString[i_2] = '\0';
printf("%d\n", i_2);
printf("%s", revString);
}
Output:
11
dlrow olleH
Using the letters of the word the user inputs, I want to print a square by shifting the letters of the word to the left one position on each line.For example, since COMPUTERS has nine letters, its square will be nine characters across by nine characters down. In each row, each character will be shifted to the end. However, the following program only does one iteration. Please advise. Thanks!
btnDetermine.addEventListener(MouseEvent.CLICK, displayVowels);
function displayVowels(e: MouseEvent): void {
var str1:String;
var str2:String = "";
var i:Number;
str1 = String(txtinString.text);
i=0;
for (i=0; i<str1.length;i++){
str2 = str2 + str1.charAt(i);
}
str2 = str2 + str1.charAt();
lblString.text += str1.charAt(i) + "\r" + str2 ;
}
function displayVowels(e:MouseEvent):void {
//defines your original string
var myString:String = String(txtinString.text);
//the total character length of the original text, determine how many lines to print
var tLength:int = myString.length;
//clears out the textfield in case theres already something on it
lblString.text = "";
//print the first line
lblString.appendText(myString);
//this loops through every line except line1, we printed line1 above
//thus tLength - 1
for (var line:uint = 0; line < tLength - 1; line++) {
//line break
lblString.appendText("\n");
//shift the characters
myString = shiftChar(myString);
//print the result into the textfield
//use appendText instead of textfield += "new text'
lblString.appendText(myString);
}
}
function shiftChar(_myString:String):String {
//save the char at the front, add it to the back later
var offset:String = _myString.charAt(0);
//slice the original string so that the first char is now removed
_myString = _myString.slice(1, _myString.length);
//add the first char of the original string to the back
_myString = _myString + offset;
//return the final results
return _myString;
}
im writing a program that looks if an entered string a palindrome is
im using c, not c++
i wrote a function to do this, the string that has been entered gets put into an array called data in the main function.
int palindroom(char data) {
length = sizeof(data); //getting the length of the word
for (i = 0; i < length; i++){
j = length-1-i; //inverting the string
resstr[i] = data[j]; //
}
if (data = resstr)
return (1); //returning result
else return (0); }
im getting the c2109 and E0142 error in visual studio but i dont really get what im doeing wrong.
(might be good to know that i just started learning c at school so im a bit new to c)
You are passing a character not a word. You need to pass the character array to pass the word.
To know the length of a null terminated string you would use strlen() function.
To reverse a string you can use strrev but you can do simpler things to know if a string is palindrome or not.
data = resstr is an assignment not comparison. And even if it was == the comparison wouldn't do what you expect. To compare strimgs you need to use strcmp().
A simpler version of what you want to do:-
int pal(char *s)
{
size_t len = strlen(s);
char *rs = s + len - 1;
while (s < rs){
if (*rs != *s)
return 0;
s++;
rs--;
}
return 1;
}
The logic is in case of palindrome the string reads same forward an dbackward.
For example
ABCBA and reverse of it is same. What we do is
ABCBA
| |
s rs <--- same
ABCBA
| |
s rs <--- same
For a nonpalindrome the check would be somethign like this:-
ABCDA
| |
s rs <-- same
ABCDA
| |
s rs <-- not same // return 0
To help you a bit regarding passing char array.
suppose you read a string like this :-
char s[50]; // you will check 49 letter words atmost;
scanf("%49s", s);
if( pal(s) ){
puts("found a palindrome");
}
else {
puts("Non-palindrome");
}
There is a series of problem with your code.
int palindroom(char data)
Here data expects a single character but you pass a pointer to char to it.
length = sizeof(data);
The function you need is not sizeof() but strlen().
if (data = resstr)
Here, first of all '=' is an assignment operator while the operator for comparison is '=='. But, '==' will also not work for strings. You need strcmp() for that.
Reference :
https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm
https://www.tutorialspoint.com/c_standard_library/c_function_strlen.htm
Code
int palindroom(char * data) {
length = strlen(data); //getting the length of the word
for (i = 0; i < length; i++){
j = length-1-i; //inverting the string
resstr[i] = data[j]; //
}
if (strcmp(resstr, data) == 0)
return (1); //returning result
else return (0);
}
I have a problem importing a text file to an array and put each character in it's own index?
Here is my code:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write("Letter: " + letter);
// Console.WriteLine(letter);
}
}
}
The problem is it only display some of the characters? Now if I change the code a little to this:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write("Letter: " + letter);
//Console.WriteLine(letter);
}
}
}
Then it display all the charaters in the array, but when I try to find out what index each character are in and add the 'i' to this code Console.Write("Letter: " + letter); so the code looks like this:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write(" Letter: " + letter + " " + i);
//Console.WriteLine(letter);
}
}
}
The result go crazy and look like this:
Output Vindue
The text file is the one below, and I placed it in the debug folder in my project so I didn't had to provide a path.
TextFile
I tried the following code and it seems to work, if this still doesn't work it's likely you're using the wrong encoding type and the file has a different encoding than UTF-8.
If that is the case then open the file in an editor like Notepad++ and see what the encoding for the file is
EDIT
The reason it looks like it was starting at line 191 instead of 0 was you were exceeding the buffer height of the console, so below I've added code to set the buffer height to it's maximum. depending on the application you might want to use a smaller value.
class Program{
static void Main(string[] args){
//Increase Console Buffer Height
Console.BufferHeight = Int16.MaxValue - 1;
string content = File.ReadAllText(#"Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
// Loop through array
for (int i =0; i<array.Length; i++) {
string letter = arrray[i].ToString()
.Replace("\r","\\r").Replace("\n", "\\n")
.Replace("\t","\\t").Replace(" ","<space>");
// Display each letter
Console.WriteLine("Letter {0}: {1}", i, letter);
}
Console.ReadLine();
}
}