将所有数字移动到给定字符串的开头
在本文中,我们将探讨一个常见的字符串操作问题:将所有数字移动到给定字符串的开头。此任务通常出现在数据清理或预处理中,我们需要以某种方式标准化或重新格式化字符串。一种广为使用的编程语言,以其效率和控制能力而闻名。
问题陈述
给定一个包含字母数字字符的字符串,我们的任务是将字符串中存在的所有数字移动到开头,同时保持其余字符的顺序不变。
解决方案方法
我们解决此问题的方法涉及两个关键步骤 -
分离数字和非数字 − 从左到右遍历字符串,将所有数字追加到“digits”字符串,将所有非数字追加到“nonDigits”字符串。
连接字符串 − 组合“digits”和“nonDigits”字符串,确保数字位于开头。
示例
以下是我们问题的程序 -
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char* moveDigits(char* str) {
char digits[100] = "";
char nonDigits[100] = "";
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i]))
strncat(digits, &str[i], 1);
else
strncat(nonDigits, &str[i], 1);
}
strcpy(str, digits);
strcat(str, nonDigits);
return str;
}
int main() {
char str[] = "abc123def456";
char* result = moveDigits(str);
printf("String after moving digits to the beginning: %s\n", result);
return 0;
}
输出
String after moving digits to the beginning: 123456abcdef
#include <bits/stdc++.h>
using namespace std;
// Function to move all digits to the beginning of a string
string moveDigits(string str) {
string digits = "", nonDigits = "";
for (char c : str) {
if (isdigit(c))
digits += c;
else
nonDigits += c;
}
return digits + nonDigits;
}
int main() {
string str = "abc123def456";
string result = moveDigits(str);
cout << "String after moving digits to the beginning: " << result << endl;
return 0;
}
输出
String after moving digits to the beginning: 123456abcdef
public class Main {
static String moveDigits(String str) {
StringBuilder digits = new StringBuilder();
StringBuilder nonDigits = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c))
digits.append(c);
else
nonDigits.append(c);
}
return digits.toString() + nonDigits.toString();
}
public static void main(String[] args) {
String str = "abc123def456";
String result = moveDigits(str);
System.out.println("String after moving digits to the beginning: " + result);
}
}
输出
String after moving digits to the beginning: 123456abcdef
def move_digits(string):
digits = ""
non_digits = ""
for char in string:
if char.isdigit():
digits += char
else:
non_digits += char
return digits + non_digits
str = "abc123def456"
result = move_digits(str)
print("String after moving digits to the beginning:", result)
输出
String after moving digits to the beginning: 123456abcdef
解释
让我们考虑字符串 -
str = "abc123def456"
分离数字和非数字后,我们得到
digits = "123456", nonDigits = "abcdef"
通过连接这两个字符串(数字在前),我们得到结果
result = "123456abcdef"
结论
将所有数字移动到字符串开头的任务是学习各种编程语言中字符串操作的有用练习。它提供了宝贵的见解,了解我们如何根据某些条件遍历和修改字符串。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP