將所有數字移動到給定字串的開頭
在本文中,我們將探討一個常見的字串操作問題:將所有數字移動到給定字串的開頭。此任務通常出現在資料清理或預處理中,我們需要以某種方式標準化或重新格式化字串。一種廣為使用的程式語言,以其效率和控制能力而聞名。
問題陳述
給定一個包含字母數字字元的字串,我們的任務是將字串中存在的所有數字移動到開頭,同時保持其餘字元的順序不變。
解決方案方法
我們解決此問題的方法涉及兩個關鍵步驟 -
分離數字和非數字 − 從左到右遍歷字串,將所有數字追加到“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"
結論
將所有數字移動到字串開頭的任務是學習各種程式語言中字串操作的有用練習。它提供了寶貴的見解,瞭解我們如何根據某些條件遍歷和修改字串。
廣告