How to use an array in an if statement - arrays

I am writing the following code including two if statements in swift 5, where I am splitting a sentence into an array including words and punctuations (How to split a sentence into words as well as punctuations and spaces? [Swift]).
As I use similar if statements a lot, it is getting annoying to modify one by one. Is there any way I can make it easier to modify if necessary? (for example by using an array)
The array I am thinking about looks as follows (please pretend that this includes the same characters in the first and the second if-statements in the code..):
let characterToStartNewWord: [String] = [" ","(",")","-", "—", "`", "‘", "/", "*","”", "[", "]", "—", "“", ":", ";", "!", "?"]
code
func sentenceSplitter(text_input: String) -> [String] {
// delete "- "
let text: String = text_input.replacingOccurrences(of: "- ", with: "")
var list = [String]()
let characterToStartNewWord: [String] = [" ","(",")","-", "—", "`", "‘", "/", "*","”", "[", "]", "—", "“"]
var currentSubString = "";
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: String.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, value) in
if let _subString = substring {
if (!currentSubString.isEmpty &&
(_subString.compare(" ") == .orderedSame
|| _subString.compare(",") == .orderedSame
|| _subString.compare(".") == .orderedSame
|| _subString.compare(";") == .orderedSame
|| _subString.compare("!") == .orderedSame
|| _subString.compare("?") == .orderedSame
|| _subString.compare(":") == .orderedSame
|| _subString.compare("(") == .orderedSame
|| _subString.compare(")") == .orderedSame
|| _subString.compare("-") == .orderedSame
|| _subString.compare("“") == .orderedSame
|| _subString.compare("*") == .orderedSame
|| _subString.compare("/") == .orderedSame
|| _subString.compare("[") == .orderedSame
|| _subString.compare("]") == .orderedSame
|| _subString.compare("—") == .orderedSame
|| _subString.compare("‘") == .orderedSame
|| _subString.compare("`") == .orderedSame
)
) {
//create word if see any of those character and currentSubString is not empty
list.append(currentSubString)
if _subString == " " {
list.append(_subString)
}
currentSubString = _subString.trimmingCharacters(in: CharacterSet.whitespaces)
characterToStartNewWord.forEach{
if _subString == $0 && _subString != " " {
list.append(_subString)
currentSubString = currentSubString.trimmingCharacters(in: CharacterSet(charactersIn: $0))
}
}
} else {
if (
_subString.compare(" ") != .orderedSame &&
_subString.compare("(") != .orderedSame &&
_subString.compare(")") != .orderedSame &&
_subString.compare("-") != .orderedSame &&
_subString.compare("*") != .orderedSame &&
_subString.compare("”") != .orderedSame &&
_subString.compare("—") != .orderedSame &&
_subString.compare("`") != .orderedSame &&
_subString.compare("‘") != .orderedSame &&
_subString.compare("/") != .orderedSame &&
_subString.compare("[") != .orderedSame &&
_subString.compare("]") != .orderedSame &&
_subString.compare("—") != .orderedSame &&
_subString.compare("‘") != .orderedSame &&
_subString.compare("`") != .orderedSame)
{
currentSubString += _subString
} else {
characterToStartNewWord.forEach{
if _subString == $0 {
list.append(_subString)
}
}
}
}
}
}
//last word
if (!currentSubString.isEmpty) {
list.append(currentSubString)
}
return list
}

No need to use an array. You can simply use a string (collection of characters) to initialize a set and check if it contains or not a character:
let characters = Set(#",;:!?()-*”—`‘/[]—"#)
if characters.contains(char) {
// code
}
If you just need to check if a string starts or not with one of those characters:
let string = "[Test]"
if let first = string.first, characters.contains(first) {
print(true)
}
edit/update:
In your case (I have not tested the code below):
func sentenceSplitter(text_input: String) -> [String] {
let text = text_input.replacingOccurrences(of: "- ", with: "")
var list = [String]()
let characterToStartNewWord = Set(#" ()-—`‘/*”[]—"#)
var currentSubString = ""
text.enumerateSubstrings(
in: text.startIndex...,
options: .byComposedCharacterSequences
) { substring, substringRange, enclosingRange, stop in
if let subString = substring {
if currentSubString.count == 1,
characterToStartNewWord.contains(subString[subString.startIndex]) {
list.append(currentSubString)
if subString == " " { list.append(subString) }
currentSubString = subString.trimmingCharacters(in: .whitespaces)
characterToStartNewWord.forEach {
if subString == String($0),
subString != " " {
list.append(subString)
currentSubString = currentSubString.trimmingCharacters(in: CharacterSet(charactersIn: String($0)))
}
}
} else {
let charSet = Set(" ()-*”—‘/[]—`")
if subString.count == 1, !charSet.contains(subString[subString.startIndex]) {
currentSubString += subString
} else {
characterToStartNewWord.forEach {
if subString == String($0) {
list.append(subString)
}
}
}
}
}
}
}

Related

Some Errors in my X and O game ( C language)

What I'm trying to do here is a tie toe game, but when my code enters the do - while part, it ends the process by itself. Since I could not solve this part, I did not have a chance to try whether there are other problems with the code, unfortunately, I would be glad if you could help with this issue.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char box_area[] = { '0','1','2','3','4','5','6','7','8','9' };
struct Player {
bool turn;
char mark;
int ID;
};
int main()
{
int return_result;
int player_number;
struct Player player1;
struct Player player2;
struct Player users[2];
users[0] = player1;
users[1] = player2;
(player1.mark = 'X') && (player2.mark = 'O');
(player1.turn = true) && (player2.turn = false);
(player1.ID = 1) && (player2.ID = 2);
do
{
box_creat();
for (int i = 0; i < 2; i++) {
if (users[i].turn == true)
{
make_move(users[i].ID);
box_creat();
users[i].turn = false;
users[i + 1].turn = true; \\ I made the logic of this section wrong
\\I will try to fix it, I realized after I sent the question
}
}
return_result = check_the_winner();
} while (return_result == 1 || return_result == -1);
return 0;
}
void box_creat(void) {
printf("| %c | %c | %c |", box_area[0], box_area[1], box_area[2]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[3], box_area[4], box_area[5]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[6], box_area[7], box_area[8]);
}
void make_move(int Player_ID)
{
int choice;
printf("Please select a area between 0-9 ");
scanf("%d", choice);
if (choice == '0' && box_area[0] == '0')
{
if (Player_ID == 1) {
box_area[0] = 'X';
}
else {
box_area[0] = 'O';
}
}
else if (choice == '1' && box_area[1] == '1')
{
if (Player_ID == 1) {
box_area[1] = 'X';
}
else {
box_area[1] = 'O';
}
}
else if (choice == '2' && box_area[2] == '2')
{
if (Player_ID == 1) {
box_area[2] = 'X';
}
else {
box_area[2] = 'O';
}
}
else if (choice == '3' && box_area[3] == '0')
{
if (Player_ID == 1) {
box_area[3] = 'X';
}
else {
box_area[3] = 'O';
}
}
else if (choice == '4' && box_area[4] == '0')
{
if (Player_ID == 1) {
box_area[4] = 'X';
}
else {
box_area[4] = 'O';
}
}
else if (choice == '5' && box_area[5] == '0')
{
if (Player_ID == 1) {
box_area[5] = 'X';
}
else {
box_area[5] = 'O';
}
}
else if (choice == '6' && box_area[6] == '0')
{
if (Player_ID == 1) {
box_area[6] = 'X';
}
else {
box_area[6] = 'O';
}
}
else if (choice == '7' && box_area[7] == '0')
{
if (Player_ID == 1) {
box_area[7] = 'X';
}
else {
box_area[7] = 'O';
}
}
else if (choice == '8' && box_area[8] == '0')
{
if (Player_ID == 1) {
box_area[8] = 'X';
}
else {
box_area[8] = 'O';
}
}
}
int check_the_winner(void)
{
if (box_area[0] && box_area[1] && box_area[2] == 'X' || 'O') {
return 1;
}
else if(box_area[3] && box_area[4] && box_area[5] == 'X' || 'O') {
return 1;
}
else if (box_area[6] && box_area[7] && box_area[8] == 'X' || 'O') {
return 1;
}
else if (box_area[2] && box_area[4] && box_area[6] == 'X' || 'O') {
return 1;
}
else if (box_area[0] && box_area[3] && box_area[6] == 'X' || 'O') {
return 1;
}
else if (box_area[2] && box_area[8] && box_area[5] == 'X' || 'O') {
return 1;
}
else if (box_area[0] && box_area[4] && box_area[8] == 'X' || 'O') {
return 1;
}
else if (box_area[1] && box_area[4] && box_area[7] == 'X' || 'O') {
return 1;
}
else {
return -1;
}
}
I tried out your program and found a few glitches that needed revision as well as adding in some additional bits of code just to neaten things up a bit. Following is your code with those revisions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char box_area[] = { '0','1','2','3','4','5','6','7','8','9' };
struct Player
{
bool turn;
char mark;
int ID;
};
void box_creat(void)
{
printf("| %c | %c | %c |", box_area[0], box_area[1], box_area[2]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[3], box_area[4], box_area[5]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[6], box_area[7], box_area[8]);
printf("\n"); /* Added for aesthetics */
}
void make_move(int Player_ID)
{
int choice;
printf("Player %d - please select a area between 0-9 ", Player_ID);
scanf("%d", &choice); /* Corrected missing ampersand */
printf("Player: %d makes a move\n", Player_ID);
if (choice == 0 && box_area[0] == '0') /* FYI - '0' is equivalent to integer value 48 */
{
if (Player_ID == 1)
{
box_area[0] = 'X';
}
else
{
box_area[0] = 'O';
}
}
else if (choice == 1 && box_area[1] == '1')
{
if (Player_ID == 1)
{
box_area[1] = 'X';
}
else
{
box_area[1] = 'O';
}
}
else if (choice == 2 && box_area[2] == '2')
{
if (Player_ID == 1)
{
box_area[2] = 'X';
}
else
{
box_area[2] = 'O';
}
}
else if (choice == 3 && box_area[3] == '3')
{
if (Player_ID == 1)
{
box_area[3] = 'X';
}
else
{
box_area[3] = 'O';
}
}
else if (choice == 4 && box_area[4] == '4')
{
if (Player_ID == 1)
{
box_area[4] = 'X';
}
else
{
box_area[4] = 'O';
}
}
else if (choice == 5 && box_area[5] == '5')
{
if (Player_ID == 1)
{
box_area[5] = 'X';
}
else
{
box_area[5] = 'O';
}
}
else if (choice == 6 && box_area[6] == '6')
{
if (Player_ID == 1)
{
box_area[6] = 'X';
}
else
{
box_area[6] = 'O';
}
}
else if (choice == 7 && box_area[7] == '7')
{
if (Player_ID == 1)
{
box_area[7] = 'X';
}
else
{
box_area[7] = 'O';
}
}
else if (choice == 8 && box_area[8] == '8')
{
if (Player_ID == 1)
{
box_area[8] = 'X';
}
else
{
box_area[8] = 'O';
}
}
}
int check_the_winner(void)
{
if ((box_area[0] == box_area[1]) && (box_area[1] == box_area[2]) && (box_area[0] != '0')) /* Corrected the testing for proper "and" conditioning */
{
return 1;
}
else if ((box_area[3] == box_area[4]) && (box_area[4] == box_area[5]) && (box_area[3] != '3'))
{
return 1;
}
else if ((box_area[6] == box_area[7]) && (box_area[7] == box_area[8]) && (box_area[6] != '6'))
{
return 1;
}
else if ((box_area[2] == box_area[4]) && (box_area[4] == box_area[6]) && (box_area[2] != '2'))
{
return 1;
}
else if ((box_area[0] == box_area[3]) && (box_area[3] == box_area[6]) && (box_area[0] != '0'))
{
return 1;
}
else if ((box_area[2] == box_area[5]) && (box_area[5] == box_area[8]) && (box_area[2] != '2'))
{
return 1;
}
else if ((box_area[0] == box_area[4]) && (box_area[4] == box_area[8]) && (box_area[4] != '4'))
{
return 1;
}
else if ((box_area[1] == box_area[4]) && (box_area[4] == box_area[7]) && (box_area[1] != '1'))
{
return 1;
}
else
{
return -1;
}
}
int main()
{
int return_result;
//int player_number; /* Compiler said that this wasn't being used */
int swap = 1;
int i;
struct Player player1;
struct Player player2;
struct Player *users[2]; /* Used these as address pointers to player "1" and player "2" */
users[0] = &player1; /* Before making these pointers, the users array just contained copies of the player structures */
users[1] = &player2;
(player1.mark = 'X') && (player2.mark = 'O');
(player1.turn = true) && (player2.turn = false);
(player1.ID = 1) && (player2.ID = 2);
do
{
box_creat();
swap += 1;
i = swap % 2;
if (i == 1)
{
make_move(users[1]->ID);
//box_creat(); /* Being performed at the top of the loop */
users[0]->turn = false;
users[1]->turn = true;
}
else
{
make_move(users[0]->ID);
//box_creat();
users[1]->turn = false;
users[0]->turn = true;
}
return_result = check_the_winner();
if (check_the_winner() == 1) /* Added when a winner has been sensed */
{
box_creat();
if (i == 1)
{
printf("Player 2 won!\n");
}
else
{
printf("Player 1 won!\n");
}
}
}
while (return_result != 1);
return 0;
}
I added comments to most of the places I had tweaked, but here are the highlights:
I shuffled some of the functions around so that the "main" function followed all of the helper functions (the compiler was giving warnings about the original sequence of the function positions).
I corrected the "choice" tests as "choice" is an integer, so the test of "choice" needed to be compared to an integer value (e.g. zero) as opposed to character '0' (which actually has a value of 48).
The tests for three letters in a row for either player do not work in that manner. Either a test needed to be made for each box for a certain row needed to tested for an "X" or an "O", and then if that test was true the test needed to be continued for the next box in the row, and then again for the third box in the row. In lieu of that route, the test was revised to basically say "if the character in the first box in the row is the same as the character in the second box in the row, and the character in the second box in the row is the same as the character in the third box in the row, and the first box does not contain a digit character (which means is contains an "X" or an "O"), then there is a winner.
It appears that an attempt was made to mirror the contents of "Player1" and "Player2" into an array of player structures. Although initially, structure "users[0]" contained the same data as "Player1" and structure "users[1]" contained the same data as "Player2", once the data in "Player1" and "Player2" were updated, those changes did to propagate over to the "users" array. So to utilize "users" in the spirit of this program, they were defined as pointers to their respective player structures.
Those were the most significant bits. The other bits were added for a logical conclusion of the game. Note that no logic was added for a draw.
Give that a test and see if that clarifies things and follows the spirit of the project.

How to split a sentence into words as well as punctuations and spaces? [Swift]

I would like to use swift 5 to programmatically split a sentence into words as well as punctuations including spaces.
input: "Hello, I am Albert Einstein."
output: ["Hello", ",", " ", "I", " ", "am", " ", "Albert", " ", "Einstein", "."]
I adopted the code provided by #Duyen-Hoa (Split text into array while maintaining the punctuation in Swift) and slightly modified it into the following code (I basically just deleted the parts deleting the space). But, I cannot get arraies for including just a space. Instead, I am somehow getting space included at the beginning of the array with each word.
func sentenceSplitter(text_input: String) -> [String] {
var list = [String]()
var currentSubString = "";
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: String.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, value) in
if let _subString = substring {
if (!currentSubString.isEmpty &&
(_subString.compare(" ") == .orderedSame
|| _subString.compare(",") == .orderedSame
|| _subString.compare(".") == .orderedSame
|| _subString.compare(";") == .orderedSame
|| _subString.compare("!") == .orderedSame
|| _subString.compare("?") == .orderedSame
)
) {
//create word if see any of those character and currentSubString is not empty
list.append(currentSubString)
currentSubString = _subString
} else {
currentSubString += _subString
}
}
}
//last word
if (!currentSubString.isEmpty) {
list.append(currentSubString)
}
return list
}
Could you let me know what I am doing wrong?
Original code from: Duyen-Hoa
var str = "Hello, I am Albert Einstein."
var list = [String]()
var currentSubString = "";
//enumerate to get all characters including ".", ",", ";", " "
str.enumerateSubstrings(in: str.startIndex..<str.endIndex, options: String.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, value) in
if let _subString = substring {
if (!currentSubString.isEmpty &&
(_subString.compare(" ") == .orderedSame
|| _subString.compare(",") == .orderedSame
|| _subString.compare(".") == .orderedSame
|| _subString.compare(";") == .orderedSame
)
) {
//create word if see any of those character and currentSubString is not empty
list.append(currentSubString)
currentSubString = _subString.trimmingCharacters(in: CharacterSet.whitespaces )
} else {
//add to current sub string if current character is not space.
if (_subString.compare(" ") != .orderedSame) {
currentSubString += _subString
}
}
}
}
//last word
if (!currentSubString.isEmpty) {
list.append(currentSubString)
}
Here you don't need to remove
.trimmingCharacters(in: CharacterSet.whitespaces)
Instead you need to detect where it's ignoring space from the _subString and there you need to add
if _subString == " " {
list.append(_subString)
}
And your code will look like below:
let str = "Hello, I am Albert Einstein."
var list = [String]()
var currentSubString = "";
str.enumerateSubstrings(in: str.startIndex..<str.endIndex, options: String.EnumerationOptions.byComposedCharacterSequences) { (substring, substringRange, enclosingRange, value) in
if let _subString = substring {
if (!currentSubString.isEmpty &&
(_subString.compare(" ") == .orderedSame
|| _subString.compare(",") == .orderedSame
|| _subString.compare(".") == .orderedSame
|| _subString.compare(";") == .orderedSame
)
) {
list.append(currentSubString)
//If _subString is a space
if _subString == " " {
list.append(_subString)
}
currentSubString = _subString.trimmingCharacters(in: CharacterSet.whitespaces)
} else {
if (_subString.compare(" ") != .orderedSame) {
currentSubString += _subString
} else {
//If _subString is a space at start
if _subString == " " {
list.append(_subString)
}
}
}
}
}
if (!currentSubString.isEmpty) {
list.append(currentSubString)
}
print(list)
Here input is "Hello, I am Albert Einstein."
And output will be:
["Hello", ",", " ", "I", " ", "am", " ", "Albert", " ", "Einstein", "."]
Hope it will help.

Why does this C code give me a segmentation fault?

Using the CS50 library, this is my code but it keeps giving me a segmentation fault. I have tried to figure out where it keeps doing a segmentation fault, and for some reason it has to do with my function. Why does it keep doing this?
#import <cs50.h>
#import <stdio.h>
#import <ctype.h>
#import <string.h>
string ciphertext(string plaintext[1], string key[1]);
int main(int argc, string argv[])
{
// Variables
string plaintext2[1];
if (argc == 2)
{
if(strlen(argv[1]) == 26)
{
string text = get_string("plaintext: ");
plaintext2[0] = text;
}
else
{
printf("Key must contain 26 characters.\n");
return 1;
}
}
else
{
printf("Usage: ./substitution key\n");
return 1;
}
string ciphertext2 = ciphertext(&plaintext2[0], &argv[1]);
printf("ciphertext: %s\n", ciphertext2);
}
string ciphertext(string plaintext[1], string key[1])
{
// Variables
string ciphertext[1];
for (int i = 0; i < strlen(plaintext[0]); i++)
{
if (plaintext[0][i] == 'a')
{
ciphertext[0][i] = tolower(key[0][0]);
}
else if (plaintext[0][i] == 'A')
{
ciphertext[0][i] = toupper(key[0][0]);
}
else if (plaintext[0][i] == 'b')
{
ciphertext[0][i] = tolower(key[0][1]);
}
else if (plaintext[0][i] == 'B')
{
ciphertext[0][i] = toupper(key[0][1]);
}
else if (plaintext[0][i] == 'c')
{
ciphertext[0][i] = tolower(key[0][2]);
}
else if (plaintext[0][i] == 'C')
{
ciphertext[0][i] = toupper(key[0][2]);
}
else if (plaintext[0][i] == 'd')
{
ciphertext[0][i] = tolower(key[0][3]);
}
else if (plaintext[0][i] == 'D')
{
ciphertext[0][i] = toupper(key[0][3]);
}
else if (plaintext[0][i] == 'e')
{
ciphertext[0][i] = tolower(key[0][4]);
}
else if (plaintext[0][i] == 'E')
{
ciphertext[0][i] = toupper(key[0][4]);
}
else if (plaintext[0][i] == 'f')
{
ciphertext[0][i] = tolower(key[0][5]);
}
else if (plaintext[0][i] == 'F')
{
ciphertext[0][i] = toupper(key[0][5]);
}
else if (plaintext[0][i] == 'g')
{
ciphertext[0][i] = tolower(key[0][6]);
}
else if (plaintext[0][i] == 'G')
{
ciphertext[0][i] = toupper(key[0][6]);
}
else if (plaintext[0][i] == 'h')
{
ciphertext[0][i] = tolower(key[0][7]);
}
else if (plaintext[0][i] == 'H')
{
ciphertext[0][i] = toupper(key[0][7]);
}
else if (plaintext[0][i] == 'i')
{
ciphertext[0][i] = tolower(key[0][8]);
}
else if (plaintext[0][i] == 'I')
{
ciphertext[0][i] = toupper(key[0][8]);
}
else if (plaintext[0][i] == 'j')
{
ciphertext[0][i] = tolower(key[0][9]);
}
else if (plaintext[0][i] == 'J')
{
ciphertext[0][i] = toupper(key[0][9]);
}
else if (plaintext[0][i] == 'k')
{
ciphertext[0][i] = tolower(key[0][10]);
}
else if (plaintext[0][i] == 'K')
{
ciphertext[0][i] = toupper(key[0][10]);
}
else if (plaintext[0][i] == 'l')
{
ciphertext[0][i] = tolower(key[0][11]);
}
else if (plaintext[0][i] == 'L')
{
ciphertext[0][i] = toupper(key[0][11]);
}
else if (plaintext[0][i] == 'm')
{
ciphertext[0][i] = tolower(key[0][12]);
}
else if (plaintext[0][i] == 'M')
{
ciphertext[0][i] = toupper(key[0][12]);
}
else if (plaintext[0][i] == 'n')
{
ciphertext[0][i] = tolower(key[0][13]);
}
else if (plaintext[0][i] == 'N')
{
ciphertext[0][i] = toupper(key[0][13]);
}
else if (plaintext[0][i] == 'o')
{
ciphertext[0][i] = tolower(key[0][14]);
}
else if (plaintext[0][i] == 'O')
{
ciphertext[0][i] = toupper(key[0][14]);
}
else if (plaintext[0][i] == 'p')
{
ciphertext[0][i] = tolower(key[0][15]);
}
else if (plaintext[0][i] == 'P')
{
ciphertext[0][i] = toupper(key[0][15]);
}
else if (plaintext[0][i] == 'q')
{
ciphertext[0][i] = tolower(key[0][16]);
}
else if (plaintext[0][i] == 'Q')
{
ciphertext[0][i] = toupper(key[0][16]);
}
else if (plaintext[0][i] == 'r')
{
ciphertext[0][i] = tolower(key[0][17]);
}
else if (plaintext[0][i] == 'R')
{
ciphertext[0][i] = toupper(key[0][17]);
}
else if (plaintext[0][i] == 's')
{
ciphertext[0][i] = tolower(key[0][18]);
}
else if (plaintext[0][i] == 'S')
{
ciphertext[0][i] = toupper(key[0][18]);
}
else if (plaintext[0][i] == 't')
{
ciphertext[0][i] = tolower(key[0][19]);
}
else if (plaintext[0][i] == 'T')
{
ciphertext[0][i] = toupper(key[0][19]);
}
else if (plaintext[0][i] == 'u')
{
ciphertext[0][i] = tolower(key[0][20]);
}
else if (plaintext[0][i] == 'U')
{
ciphertext[0][i] = toupper(key[0][20]);
}
else if (plaintext[0][i] == 'v')
{
ciphertext[0][i] = tolower(key[0][21]);
}
else if (plaintext[0][i] == 'V')
{
ciphertext[0][i] = toupper(key[0][21]);
}
else if (plaintext[0][i] == 'w')
{
ciphertext[0][i] = tolower(key[0][22]);
}
else if (plaintext[0][i] == 'W')
{
ciphertext[0][i] = toupper(key[0][22]);
}
else if (plaintext[0][i] == 'x')
{
ciphertext[0][i] = tolower(key[0][23]);
}
else if (plaintext[0][i] == 'X')
{
ciphertext[0][i] = toupper(key[0][23]);
}
else if (plaintext[0][i] == 'y')
{
ciphertext[0][i] = tolower(key[0][24]);
}
else if (plaintext[0][i] == 'Y')
{
ciphertext[0][i] = toupper(key[0][24]);
}
else if (plaintext[0][i] == 'z')
{
ciphertext[0][i] = tolower(key[0][25]);
}
else if (plaintext[0][i] == 'Z')
{
ciphertext[0][i] = toupper(key[0][25]);
}
else
{
ciphertext[0][i] = plaintext[0][i];
}
}
return ciphertext[0];
}
I really need some help, and I don't know why it keeps giving a fault.
The array
string ciphertext[1];
is uninitialized and has indeterminate value.
Accessing such an array the way like this
ciphertext[0][i] = tolower(key[0][0]);
results in undefined behavior.
You need to allocate a character array with the size equal to the value of the expression
strlen( *plaintext ) + 1
Pay attention to that instead the numerous if-else statement you could define a string literal like for example
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
and then you can use the standard string function strchr like
char *p = strchr( letters, toupper( ( unsigned char)plaintext[0][i] ) );
if ( p != NULL )
{
if ( plaintext[0][i] == *p )
{
ciphertext[0][i] = key[0][p - letters]);
}
else
{
ciphertext[0][i] = tolower(key[0][p - letters]);
}
}
You already have the answer (#Vlad from Moscow), but I would like to point out a few things:
Duplicating is a very bad practice, it is unreadable and more important seriously time-consuming. If you see "100" else if() statements one below the other you should suspect that something is terribly wrong with your code.
Try your best to avoid using numbers in your code. What if you want to change a value that you already copy-pasted a hundred times? Instead of using numbers, I would advise you to use variables and symbolic constants
Try to improve your current code, you can write something like this:
for (int i = 0; i < strlen(plaintext[0]); i++)
{
int ind = 0;
int lower_case = 97, upper_case = 65;
if (plaintext[0][i] == lower_case)
{
ciphertext[0][i] = tolower(key[0][ind]);
}
else if (plaintext[0][i] == upper_case)
{
ciphertext[0][i] = toupper(key[0][ind]);
}
ind++; lower_case++; upper_case++;
}

convert amount in words in angularjs

I need to convert amount in words. For example, the amount I will get it from service is 9876, I need to display in a table "Nine Thousand Eight Hundred and Seventy Six" in a table.
I need to do this using angularjs. Please help me how can I do this.
JSFIDDLE
function convertNumberToWords(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
}
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=convertNumberToWords(this.value)" />
<div id="word"></div>
I refered this javascript fiddle. But I want to it in a angularjs.
I used this for Angular 8.
Input : 123456789.09 Output : twelve crore thirty four lakh fifty six thousand seven eighty nine point zero nine
n: string;
a = ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
ngOnInit(): void {
console.log(this.inWords(123456789.09));
}
inWords (num): string {
num = Math.floor(num * 100);
if ((num = num.toString()).length > 11) { return 'overflow'; }
let n;
n = ('00000000' + num).substr(-11).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})(\d{1})(\d{1})$/);
if (!n) { return; } let str = '';
// tslint:disable-next-line:triple-equals
str += (n[1] != 0) ? (this.a[Number(n[1])] || this.b[n[1][0]] + ' ' + this.a[n[1][1]]) + 'crore ' : '';
// tslint:disable-next-line:triple-equals
str += (n[2] != 0) ? (this.a[Number(n[2])] || this.b[n[2][0]] + ' ' + this.a[n[2][1]]) + 'lakh ' : '';
// tslint:disable-next-line:triple-equals
str += (n[3] != 0) ? (this.a[Number(n[3])] || this.b[n[3][0]] + ' ' + this.a[n[3][1]]) + 'thousand ' : '';
// tslint:disable-next-line:triple-equals
str += (n[4] != 0) ? (this.a[Number(n[4])] || this.b[n[4][0]] + ' ' + this.a[n[4][1]]) : 'hundred';
// tslint:disable-next-line:triple-equals
str += (n[5]) ? (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' + this.a[n[5][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[6]) ? ((str != '') ? 'point ' : '') + (this.a[Number(n[6])] || this.b[n[6][0]] + ' ' + this.a[n[6][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[7] != 0) ? (this.a[Number(n[7])] || this.b[n[7][0]] + ' ' + this.a[n[7][1]]) : '';
return str;
}
Define a filter to convert number to word such as following code:
angular.module('myModuleName')
.filter('convertToWord', function() {
return function(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
};
});
Then in your templates (views) use this filter as follow:
{{amount | converToWord}}
For example to show inserted value in an input field:
<input type="text" name="number" placeholder="Number OR Amount" ng-model="myValue" />
<div id="word">{{myValue | convertToWord}}</div>

Argument Out Of Range Exception, what to do

I'm trying to make hacker game, I have own cmd, where I typing commnads, but I'm getting this problem and I don't know what I'm doing bad.
This is the first code in Program.cs
if (enter == "del" + space + FIles.files1[0] && admin == true && connected == true && cdMain == true )
{
FIles.files1.RemoveAt(0);
Console.WriteLine("");
FIles.files1.ForEach(Console.WriteLine);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(successfull);
Console.ForegroundColor = ConsoleColor.Green;
}
if (enter == "del" + space + FIles.files1[1] && admin == true && connected == true && cdMain == true)
{
FIles.files1.RemoveAt(1);
Console.WriteLine("");
FIles.files1.ForEach(Console.WriteLine);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(successfull);
Console.ForegroundColor = ConsoleColor.Green;
}
if (enter == "del" + space + FIles.files1[2] && admin == true && connected == true && cdMain == true)
{
FIles.files1.RemoveAt(2);
Console.WriteLine("");
FIles.files1.ForEach(Console.WriteLine);
// FIles.files1.AddRange(1);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(successfull);
Console.ForegroundColor = ConsoleColor.Green;
}
if (enter == "del" + space + FIles.files1[3] && admin == true && connected == true && cdMain == true )
{
FIles.files1.RemoveAt(3);
Console.WriteLine("");
FIles.files1.ForEach(Console.WriteLine);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(successfull);
Console.ForegroundColor = ConsoleColor.Green;
}
and here is a second with List
class FIles
{
public static List<string> files1 = new List<string>();
public static void Files1()
{
files1.Add("file1.exe");
files1.Add("file2.exe");
files1.Add("file3.exe");
files1.Add("file4.exe");
files1.Add("file5.exe");
}
}
Error arrive when I try to delete the thirth, please help.
What about this:
for(int i = 0; i < ExampleList.Count; i++)
{
if (enter == "del" + space + FIles.files1[i] && admin == true && connected == true && cdMain == true )
{
FIles.files1.RemoveAt(i);
Console.WriteLine("");
FIles.files1.ForEach(Console.WriteLine);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(successfull);
Console.ForegroundColor = ConsoleColor.Green;
}
}
The problem with your code is that the size of your list is changing each time you call RemoveAt. After two calls your list has a size of 3 and FIles.files1[3] is out of range.

Resources