Чтобы обрезать строку по определенному символу на различных языках программирования, вот несколько методов и примеры кода:
- JavaScript:
// Method 1: Using split() and join() functions
const str = "Hello, world!";
const trimmedStr = str.split(',')[0];
console.log(trimmedStr); // Output: "Hello"
// Method 2: Using substring() function
const str = "Hello, world!";
const commaIndex = str.indexOf(',');
const trimmedStr = str.substring(0, commaIndex);
console.log(trimmedStr); // Output: "Hello"
- Python:
# Method 1: Using split() function
str = "Hello, world!"
trimmed_str = str.split(',')[0]
print(trimmed_str) # Output: "Hello"
# Method 2: Using find() and slicing
str = "Hello, world!"
comma_index = str.find(',')
trimmed_str = str[:comma_index]
print(trimmed_str) # Output: "Hello"
- Java:
// Method 1: Using split() function
String str = "Hello, world!";
String trimmedStr = str.split(",")[0];
System.out.println(trimmedStr); // Output: "Hello"
// Method 2: Using substring() function
String str = "Hello, world!";
int commaIndex = str.indexOf(",");
String trimmedStr = str.substring(0, commaIndex);
System.out.println(trimmedStr); // Output: "Hello"
- C#:
// Method 1: Using Split() function
string str = "Hello, world!";
string trimmedStr = str.Split(',')[0];
Console.WriteLine(trimmedStr); // Output: "Hello"
// Method 2: Using Substring() function
string str = "Hello, world!";
int commaIndex = str.IndexOf(',');
string trimmedStr = str.Substring(0, commaIndex);
Console.WriteLine(trimmedStr); // Output: "Hello"